Remove '0' Number from time 9:00 AM - c#

I have time format like 9:00AM - 10:00AM.
string startTime = "9:00AM";
string endTime = "10:00AM";
I want to display it like 9-10 AM.
How can I achieve it?

Parse your times
var sdt = DateTime.ParseExact(startTime, "h:mmtt", CultureInfo.InvariantCulture);
var edt = ...
Compare the meridian designators or check if the start is before 12 and the end is after:
if(sdt.Hour < 12 && edt.Hour >= 12)
If the times are in the same day half, use format ${sdt:h}-{edt:htt}"
If the times are in different day halves use format ${sdt:htt}-{edt:htt}"

If you have datetime, use datetime.ToString("HH");
If you don't, you can also write like that (remove AM before doing it)
Convert.ToDateTime(starttime).ToString("HH");
There are also easier ways to do it if you have fixed numbers;
starttime.Replace(":00","")

string starttime = "9:00AM";
string Endtime = "10:00AM";
starttime = starttime.Replace(":00AM","");
Endtime = Endtime.Replace(":00","");
var result = starttime + "-" + Endtime;
But i think you must change the Format of starttime and endtime to a TimeSpan or DateTime

Related

rounding to a specific 12hr timeframe in c#.net

I realize this may have been answered before, and I may just not be searching for the answer properly, so my apologies if this is a duplicate. This is for a c# webform.
I've got a datetime, set to now, and rounded up the nearest 30 minutes:
DateTime dtNow = RoundUp(DateTime.Now, TimeSpan.FromMinutes(30));
I'm splitting the datetime into its component parts, using M:YY tt (no preceding 0 on the month, two digit year, 12 hr am/pm)
DateString = dtNow.ToString("M/dd/yy");
TimeString = dtNow.ToString("h:mm tt");
What I want do to is simple, I want to see if that TimeString falls between 7:00pm and 5:59am, just need to round it to 6:00am of the following day (unless its past midnight, in which case 6:00am of that day).
Can anyone help me out, or at least point out where its already answered?
You should really stick to DateTime. What you want using string will always need to parse again that string into a DateTime to implement your logic.
A simple solution:
public static DateTime GetRoundedDate(DateTime originalDate)
{
if(originalDate.Hour > 19)
return originalDate.Date.AddDays(1).AddHours(6);
else if (originalDate.Hour < 6)
return originalDate.Date.AddHours(6);
return originalDate;
}
So now you may call:
DateTime dtNow = RoundUp(DateTime.Now, TimeSpan.FromMinutes(30));
var rounded = GetRoundedDate(dtNow);
DateString = rounded.ToString("M/dd/yy");
TimeString = rounded.ToString("h:mm tt");
Just look at the time properties on your DateTime object.
if (dtNow.Hour >= 19 || (dtNow is tomorrow && dtNow.Hour <= 7)) {
//do your stuff
}
where "is tomorrow" is something like dtNow.Date == DateTime.Today.AddDays(1)

Adding TimeSpan only to Time of Date and not Date

I have 2 DateTime's:
DateTime beginDate = 2000/01/01 14:00
DateTime endDate = 2000/01/01 14:30
I calculate a timespan between these 2 hours:
TimeSpan span = endDate.Subtract(beginDate);
var myValue = beginDate.AddMinutes( span.Minutes ).TimeOfDay.Ticks
//Trying to get this equal to the endDate by using the beginDate + myValue
//I have to use myvalue, because this value comes from the DB and this piece
//of code sits in another class than the above code
DateTime otherDate = beginDate.Date.Add( new TimeSpan( myValue ) )
The Problem is I keep on getting 0:30 back and I should get back 14:30.
I understand why, its because beginDate.Date gives you 2000/01/01 00:00, but I cant use beginDate.TimeOfDay.Add because it is a readonly field.
How do I achieve that it only add the myValue to the time of the given date??
You should use TimeSpan.TotalMinutes.
span.Minutes only gives you the minutes part. So of 1:30 it won't be 90. It'll be 30. Use TotalMinutes to get the 90.
Also beginDate.Date should be changed to beginDate because by using Date you are removing the time.
DateTime otherDate = beginDate + span;

How to corectly Loop over days

I am trying to make a string with start dates and end dates. That can loop over X number of days.
int nrOfDaysToLoopBy = 3;
List<string> Dates = new List<string>();
string startDate = "2014-01-01"; //this date is given to me by an api I am just hard codeing for testing
string endDate = "2014-01-30";
DateTime StartDate = DateTime.ParseExact(startDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
DateTime EndDate = DateTime.ParseExact(endDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
DateTime myDate = StartDate; // setting the initial date
for (DateTime date = StartDate.AddDays(nrOfDaysToLoopBy); date.Date <= EndDate.Date; date = date.AddDays(nrOfDaysToLoopBy))
{
Dates.Add("start-date=" + myDate.ToString("yyyy-MM-dd") + "&end-date=" + date.ToString("yyyy-MM-dd"));
myDate = date.AddDays(1);
}
// Dealing with any left over days.
if (myDate != EndDate && EndDate > myDate)
{
Dates.Add("start-date=" + myDate.ToString("yyyy-MM-dd") + "&end-date=" + EndDate.ToString("yyyy-MM-dd"));
}
My results:
start-date=2014-01-01&end-date=2014-01-04
start-date=2014-01-05&end-date=2014-01-07
The problem here is that there is 4 days between 2014-01-01 and 2014-01-04 not 3.
Results I am trying to get:
start-date=2014-01-01&end-date=2014-01-03
start-date=2014-01-04&end-date=2014-01-06
Update:
Can we agree that the days between 2014-01-01&end-date=2014-01-04 are
2014-01-01, 2014-01-02, 2014-01-03, and 2014-01-04 That's 4
I have been playing with this for a few hours now and nothing I have done has fixed the problem.
The problem here is that there is 4 days between 2014-01-01 and 2014-01-04 not 3.
One could argue that there's 3 days between 2014-01-01 and 2014-01-04: Between 2014-01-01 and 2014-01-04, three 24h periods pass:
2014-01-01 -- 2014-01-02
2014-01-02 -- 2014-01-03
2014-01-03 -- 2014-01-04
You see, the problem is how you define between. If you want to include the start and the end date, you need to adjust the number of dates you add.
Edit:
This fixed the problem. nrOfDaysToLoopBy-1
for (DateTime date = StartDate.AddDays(nrOfDaysToLoopBy-1); date.Date <= EndDate.Date; date = date.AddDays(nrOfDaysToLoopBy))
{
}
Simply change the statement:
DateTime date = StartDate.AddDays(nrOfDaysToLoopBy);
in your for loop initialization to
DateTime date = StartDate.AddDays(nrOfDaysToLoopBy-1);
The issue is that when you add days, the number of days "between" as you're calling it is actually the number of days you add + 1. So monday->monday (zero days added) is 1 day, monday->tuesday (one day added) is 2 days, etc. That's why you need the -1 modification for the start date.
The reason you don't need this alteration on every other iteration on the loop is because of the myDate = date.AddDays(1) line. This reduces the difference between myDate and date by one, bringing it back to the correct difference

DateTime.now subtraction with value from database

I need to be able to get the difference from the current date with the date from my database. If the difference is 30, I need to display a expiry date message. My code block looks as such:
var expiryDate = DateTime.Now - DateTime.Parse(user[3]);
The thing is, this returns some weird numbers which I can't seem to manage. How would I go about getting just the number of days and then check if it is 30?
Thanks for having a look guys!
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Parse(user[3]);
TimeSpan ts = dt1 - dt2;
int days = ts.Days;
if (days == 30){
//do something
}
(DateTime.Now - DateTime.Parse(user[3])).TotalDays //this will give you the days.
var timespan = DateTime.Now - DateTime.Parse(user[3]);
var days = timespan.Days;
System.TimeSpan diffResult = dt1 - dt2;
if(diffResult < 0)
{
//your code
}
When you subtract two DateTime instances you get a Timespan.
Validate your value against the TotalDays property of this timespan
var expiryDate = DateTime.Now - DateTime.Parse(user[3]);
expiryDate.TotalDays > 30 // check in this fashion

How can I get the offset as a TimeSpan if I only have the time as a string, such as 09:00 AM

I have the string "9:00 AM". I would like to get the offset from midnight as a TimeSpan in C#?
9:00 AM is a punctual time, while TimeSpan structure represents time intervals so you are trying to convert apples to oranges.
Timespan? A timespan is just a period of time. The "AM" shows that this is a specific time, so this cannot be a timespan. Or do you want to parse "9:00", without the "AM", and get a timespan of 9 hours as result?
#Your comment:
You could use a method that does this for you. Here's a simple example implementation (you would need to add better input validation, use better convert methods than just Convert.ToInt32() and so on):
public static TimeSpan GetTimeSpanFormString(string strString)
{
strString = strString.Trim();
string[] strParts = strString.Split(':', ' ');
int intHours, intMinutes;
if (strParts.Length != 3)
throw new ArgumentException("The string is not a valid timespan");
intHours = strParts[2].ToUpper() == "PM" ? Convert.ToInt32(strParts[0]) + 12 : Convert.ToInt32(strParts[0]);
intMinutes = Convert.ToInt32(strParts[1]);
return new TimeSpan(intHours, intMinutes, 0);
}
If you want the offset from midnight, you can use:
DateTime dateTime = DateTime.ParseExact( strValue, "h:mm tt" );
TimeSpan offset = dateTime - DateTime.Today;
TimeSpan.TryParse(yourString, out yourTimeSpan);

Categories