I want to do a timer and print the value in a label. I do:
label1.Text = (DateTime.Now - startDate).ToString("HH:mm:ss");
But I receive a FormatException error. What's wrong in my code?
DateTime.Now - startDate returns a TimeSpan not a DateTime.
You need to escape colons with backslash and use lowercase hh in TimeSpan.ToString:
TimeSpan diff = DateTime.Now - startDate;
label1.Text = diff.ToString("hh\\:mm\\:ss");
But note that the hour will never exceed 23 hours, the maximum value is 23:59:59. If you want to show also the days you have to use a format like "dd\\:hh\\:mm\\:ss".
label1.Text = DateTime.Compare(Convert.ToDateTime(startDate.Text), Convert.ToDateTime(ToDate.Text,"hh\\:mm\\:ss"));
Related
string date = "17:25";
if(date.Lenght == 5){
myobj.StartTime = DateTime.ParseExact(date, "HH:mm", CultureInfo.InvariantCulture);
// add only hh and minutes and preserve day and year
}
else if(date.Lenght > 5){
myobj.StartTime = DateTime.ParseExact(date, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
}
myobj.StartTime is obviously of DateTime datatype.
I know I could break this string on : and use first part as hours and then convert that to double and then use AddHours, and I should repeat that for minutes also but I'm wonder is there convenient way to do this?
You can use TimeSpan.ParseExact:
myobj.StartTime = myobj.StartTime.Add(TimeSpan.ParseExact(date, "hh\\:mm", CultureInfo.InvariantCulture));
In hh\\:mm hh are hours (you cannot use HH here, not supported by this concrete method), mm are minutes, and \\: is escaped : character. One slash is to escape slash itself in C# literal string (otherwise you can do this: #"hh\:mm"), and you need to escape : with slash in format string, because otherwise TimeSpan.ParseExact will treat it as custom format specifier (like h), but there is no such format specifier and it will throw invalid format exception.
Note that if you also allow single-digit hours and minutes (like this: "1:2" or "1:25") - then you have to use another format:
TimeSpan.ParseExact(date, #"h\:m", CultureInfo.InvariantCulture);
This format will handle both single-digit and two-digit hours and minutes.
Also note that if you have more than 24 hours in your string (like "25:11") - this method will not work and you will have to fallback to split (as far as I know).
I want get diffrences Day,Hour and Day between two days.
I use belowe Code :
DateTime LastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
int differenceDay = DateTime.Now.Subtract(LastDate).Days;
int differenceHoure = DateTime.Now.Hour - LastDate.Hour;//returns -11
int differenceMinute = DateTime.Now.Minute - LastDate.Minute;
When I want get Hours its return mines (-11 e.t).
How can I get positive Diffrence Hour ?
anyone can you help me?
I want get Last Dat and show its by string how days afterd now.
You're subtracting component-wise (i.e. "this hour-of-day minus that hour-of-day, this minute-of-hour minus that minute-of-hour"). Don't do that - it won't work if the current hour-of-day is earlier than the hour-of-day of lastDate, or the same for minute-of-hour - you get a negative value, exactly as you've seen.
Instead, subtract one DateTime from another to get a TimeSpan and use that single TimeSpan for all the components:
DateTime lastDate = DateTime.Parse("2/12/2015 11:24:23 AM");
TimeSpan difference = DateTime.Now - lastDate;
int days = difference.Days;
int hours = difference.Hours;
int minutes = difference.Minutes;
That will still be negative if lastDate is after DateTime.Now, of course.
Note that this will give you a result which is meaningful if you display all three components. For example, it might give you "2 days, 3 hours and 10 minutes". If instead you want to represent the same TimeSpan as "2.194 days" or "51.166 hours" or "3160 minutes" then you can use TotalDays, TotalHours and TotalMinutes.
If you always want a positive TimeSpan - the equivalent of Math.Abs but for TimeSpan you can just use TimeSpan.Duration():
TimeSpan difference = (DateTime.Now - lastDate).Duration();
I would like to know if there is a way to convert a 24 Hour time formatted string to a TimeSpan.
Right now I have a "old fashion style":
string stringTime = "07:35";
string[] values = stringTime.Split(':');
TimeSpan ts = new TimeSpan(values[0], values[1], 0);
While correct that this will work:
TimeSpan time = TimeSpan.Parse("07:35");
And if you are using it for validation...
TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
// handle validation error
}
Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.
If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:
DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture,
DateTimeStyles.None, out dt))
{
// handle validation error
}
TimeSpan time = dt.TimeOfDay;
As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".
Try
var ts = TimeSpan.Parse(stringTime);
With a newer .NET you also have
TimeSpan ts;
if(!TimeSpan.TryParse(stringTime, out ts)){
// throw exception or whatnot
}
// ts now has a valid format
This is the general idiom for parsing strings in .NET with the first version handling erroneous string by throwing FormatException and the latter letting the Boolean TryParse give you the information directly.
Use TimeSpan.Parse to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx
You can convert the time using the following code.
TimeSpan _time = TimeSpan.Parse("07:35");
But if you want to get the current time of the day you can use the following code:
TimeSpan _CurrentTime = DateTime.Now.TimeOfDay;
The result will be:
03:54:35.7763461
With a object cantain the Hours, Minutes, Seconds, Ticks and etc.
Currently it is evening and couldn't actually test it with morning hours like 7 in the morning.
but a code like this:
DateTime dt = DateTime.Now;
string str = dt.ToString("HH:mm");
So my question is can I be sure that it is always returning time in format like "07:35" and not "7:35" ?
DateTime.Now returns time without formatting. Format applied in the ToString("HH:mm") method. And yes, this format is 24-hour.
Yes because the documentation says:
The "HH" Custom Format Specifier: The "HH" custom format specifier (plus any number of additional "H" specifiers) represents the hour as a number from 00 through 23; that is, the hour is represented by a zero-based 24-hour clock that counts the hours since midnight. A single-digit hour is formatted with a leading zero.
You could test with
DateTime dt = DateTime.Now;
string str = dt.ToString("HH:mm");
Console.WriteLine(str);
DateTime t = new DateTime(2014,3,27,7,5,0);
str = t.ToString("H:mm");
Console.WriteLine(str);
The HH format return always the hour formatted with two digits adding a leading zero when the hour is less than 10, the H format returns the hours formatted with exactly the digits present in the hour part.
You can create an instance of DateTime with desired date and time values using to test various time setting and formats :
var dt = new DateTime(2014, 1, 1, 7, 35, 0);
string str = dt.ToString("HH:mm");
I have date/time format, for example:
"1-Mar-13 92230"
According to this document and this link the format is as follows:
"d-MMM-yy Hmmss", because:
Day is single digit, 1-30
Month is 3 letter abbreviation, Jan/Mar etc.
Year is 2 digits, eg 12/13
Hour is single digit for 24 hour clock, eg 9, 13 etc. (no 09)
Minute is standard (eg 01, 52)
Second is standard (eg 30, 02)
I'm trying to run the following code in my program, but I keep getting an error of "String was not recognized as a valid DateTime."
string input = "1-Mar-13 92330";
var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss",
System.Globalization.CultureInfo.CurrentCulture);
Please help, I'm not too familiar with DateTime conversions, but I can't see where I've gone wrong here. Thanks!
UPDATE: Is this because time cannot be parsed without colons in between? (eg 1-Mar-13 9:22:30 gets parsed, but i have an external data source that would be impossible to rewrite from Hmmss to H:mm:ss)
You could fix your date:
var parts = "1-Mar-13 92230".Split(' ');
if (parts[1].Length == 5)
{
parts[1] = "0" + parts[1];
}
var newDate = parts[0] + " " + parts[1];
var date = DateTime.ParseExact(newDate, "d-MMM-yy HHmmss", System.Globalization.CultureInfo.CurrentCulture);
From msdn:
If format is a custom format pattern that does not include date or
time separators (such as "yyyyMMdd HHmm"), use the invariant culture
for the provider parameter and the widest form of each custom format
specifier. For example, if you want to specify hours in the format
pattern, specify the wider form, "HH", instead of the narrower form,
"H".
so you can try:
string input = "1-Mar-13 92330";
var date = DateTime.ParseExact(input, "d-MMM-yy Hmmss",
System.Globalization.CultureInfo.InvariantCulture);
Your input string has to be of following format
string input = "1-Mar-13 092330";
If you go back to your link, it says
H 24-hour clock hour (e.g. 19)
Now H is 24 hours, it should be represented with leading 0. If not imagine how would you handle the case of hours greater than 9 i.e which are in double digit.
If not your hour and Minute and Seconds has to be separated.
string input = "1-Mar-13 9 2330";
var date = DateTime.ParseExact(input, "d-MMM-yy H mmss",
System.Globalization.CultureInfo.InvariantCulture);
Your hour min and seconds need to be separated, as they are not getting distinguished.
string input = "1-Mar-13 9 23 30";
var date = DateTime.ParseExact(input, "d-MMM-yy H mm ss", System.Globalization.CultureInfo.CurrentCulture);