I am trying to parse time using TimeSpan.Parse method; However i get an unexpected result as i am trying to parse this 00:00:45.748 which supposed to be
0 Hours
0 Minutes
45 Seconds
748 Milliseconds
TimeSpan.Parse("00:00:45.748")
Result :
00:00:45.7480000
I want to know why it reads the milliseconds as 7480000 instead of 748 ?
The result you are showing is that of displaying a TimeSpan in a textual format.
By default it will show the full range.
The string you have shown actually shows that the parse was successful and you got the right result.
If you want to format the TimeSpan, use ToString with an appropriate TimeSpan format string (.NET 4.0 and above).
There are custom and standard format strings for TimeSpan.
In your case, it looks like you are looking for:
myTimeSpan.ToString("hh:mm:ss.FFF")
As additional to Oded's answer;
From TimeSpan.Parse Method (String)
ff - Optional fractional seconds, consisting of one to seven decimal
digits.
You can use The "FFF" Custom Format Specifier
Like;
TimeSpan ts = TimeSpan.Parse("00:00:45.748");
Console.WriteLine(ts.ToString(#"hh\:mm\:ss\.FFF"), CultureInfo.InvariantCulture);
Output will be;
00:00:45.748
For more informations, take a look at Standard TimeSpan Format Strings and Custom TimeSpan Format Strings
00:00:45.7480000 == 00:00:45.748
The difference is simply the number of decimal places on the milliseconds
This will format your output as desired:
var ts = TimeSpan.Parse("00:00:45.748");
Console.WriteLine(string.Format("{0:dd\\:hh\\:mm\\:ss\\.fff}", ts));
The fff is the number of decimal places you want to display (this can be from 1 to 7). See http://msdn.microsoft.com/en-us/library/ee372287.aspx
Note that this will require .NET 4.0 or above
Related
I have to parse time given in hours, minutes, seconds and fraction of seconds. Such as
"15:42:58.1"
"15:42:58.21"
"15:42:58.417"
using the following code:
DateTime.ParseExact("15:42:58.1", "HH:mm:ss.0.f", CultureInfo.InvariantCulture);
This works with excactly one decimal. Any other nomber of decimal will cause an exception.
Question:
Is there a generic possibility for the number of decimals of seconds?
You can use TimeSpan if this is a time of day or similar. See Custom TimeSpan format strings. The trick from Jeroen Mostert's comment to your question still applies: Use capital Fs.
You must escape the delimiters with TimeSpan format strings. Therefore, use one of:
var ts1 = TimeSpan.ParseExact("15:42:58.1", #"hh\:mm\:ss\.FFFFFFF", CultureInfo.InvariantCulture);
var ts2 = TimeSpan.ParseExact("15:42:58.1", "hh':'mm':'ss'.'FFFFFFF", CultureInfo.InvariantCulture);
This appears to work even with trailing zeros, e.g. "15:42:58.10" parses OK.
You can use array of DateTimeFormat.
like
string[] validFormats = { "HH:mm:ss.f", "HH:mm:ss.ff", "HH:mm:ss.fff" };
DateTime.ParseExact("15:42:58.1", validFormats, CultureInfo.InvariantCulture, DateTimeStyles.None);
Now this will parse your DateTime, even if you fraction of 3 digits
.net Fiddle
How can I format a DateTime with ToString(string format) to get the Ticks value of it?
The Custom date and time format strings on MSDN doesn't detail a format for ticks. Is it really not possible to specify ticks in the format string?
i.e. where ticks gives you a value such as:
> DateTime.Now.Ticks
637014563963906371
I would like to be able to do
> DateTime.Now.ToString("qqqqqqqqqqqqqqqq")
"637014563963906371"
where qqqqqqqqqqqqqqqq is the mystery format string.
There isn't one - MSDN lists all the applicable format strings for a datetime and that page doesn't mention anything you can pass DateTime.ToString() and have it return you the ticks. If you want your ticks as a string you'll have to go as per the comments:
DateTime.Now.Ticks.ToString()
This can, of course accept format strings of its own operating as a number, for example if you wanted it in hexadecimal:
DateTime.Now.Ticks.ToString("x")
If you wanted it as part of a larger (interpolated) string, padded to 20 characters:
$"Ticks now, padded with leading zeroes to 20 wide is: {DateTime.Now.Ticks:D20}"
etc.
Note: you wrote 16 q in your "mystery format string" but ticks is already 18 digits, so unless you're trying to truncate it, bear this 18 digit minimum in mind
In C#, I am accepting 2 time values in textboxes and want to calculate the time between these 2 times. The times are accepted in 24 hour format as hhmm. There is no any semicolon or . is used in between hrs and mins.
I have tried following code :
DateTime ts1 = DateTime.Parse(TextBox3.Text);
DateTime ts2 = DateTime.Parse(TextBox4.Text);
TimeSpan ts = ts2-ts1;
TextBox12.Text = Convert.ToString(ts);
Getting the error as
String was not recognized as a valid DateTime.
Suppose TextBox3.Text = 0800 and TextBox4.Text = 2000 then TextBox12.Text = 12
Please help.
Since the format of the text in your text boxes is not the "default" date / time format the call to TimeSpan.Parse() fails / returns wrong results. (You are using a format without a colon : character for separating the hours and minutes).
In this case you'll need to specify the format explicitly, for example using the TimeSpan.ParseExact() method.
The following example parses the text "0854" into a TimeSpan value, representing the time 08:54
TimeSpan.ParseExact("0854", "hhmm", System.Globalization.CultureInfo.InvariantCulture)
You have three problems:
1) Trying to parse times as dates. Using DateTime.Parse is inappropriate here.
2) Even if you use TimeSpan.Parse, your example data does not conform to the required format for the parse method to recognise it. The accepted formats are shown here: https://msdn.microsoft.com/en-us/library/se73z7b9(v=vs.110).aspx For the time part, you would need at least to include a colon (:) between the hours and minutes in your input, e.g. 08:00.
So you can either do that, or use TimeSpan ts1 = TimeSpan.ParseExact(TextBox3.Text, "hhmm", System.Globalization.CultureInfo.InvariantCulture) in order to give it a custom format to recognise.
3) You should use the TimeSpan.Subtract method to accurately deduct one time period from the other. Currently just using - is unlikely to work, and the system will not know whether you want the output in hours, minutes, seconds or anything else.
TextBox12.Text = ts2.Subtract(ts1).Hours
Should give you what you want.
You probably ought to consider some other prior validation as well - checking that ts2 is actually greater than ts1 before allowing the input, and maybe using TryParseExact to attempt to parse the input and return true/false, in case the user has input the value incorrectly (you will get a FormatException from the Parse or ParseExact method if there's an incorrect input).
I'm trying to figure-out the right string format of the following given date-time literal:
18-JUN-13 12.17.36.000000000
Using MSDN, I managed to composed the following format:
"d'-'MMM'-'y'T'h'.'m'.'s'.'fff"
But when using the DateTime.ParseExact, the parsing fails with a FormatException: String was not recognized as a valid DateTime.
My code:
DateTime.ParseExact("18-JUN-13 12.17.36.000000000", "d'-'MMM'-'y'T'h'.'m'.'s'.'fff", null);
You can use
dd-MMM-yy hh.mm.ss.fffffff
with english based culture like InvariantCulture for example. I'm on mobile right now, so I can't try it :(
AFAIK, milliseconds part parsing limit is 7, that's why you can't parse your string without manipulate it. You can use it like;
var dt = DateTime.ParseExact("18-JUN-13 12.17.36.0000000",
"dd-MMM-yy HH.mm.ss.fffffff",
CultureInfo.InvariantCulture);
Looks like that's why probably we have The "fffffff" custom format as top character of milliseconds. From docs;
Although it is possible to display the ten millionths of a second
component of a time value, that value may not be meaningful. The
precision of date and time values depends on the resolution of the
system clock. On the Windows NT 3.5 (and later) and Windows Vista
operating systems, the clock's resolution is approximately 10-15
milliseconds.
You asked;
How would you have manipulate the string?
Well, one way to get last index of comma and substring it to 8 index after that like;
string s = "18-JUN-13 12.17.36.000000000";
var dateString = s.Substring(0, s.LastIndexOf(".") + 8);
You have a bunch of single quotes in there which isn't a correct format. Try this
DateTime.ParseExact("18-JUN-13 12.17.36.000000000", "d-MMM-yTh.m.s.fff", null);
I recently switch from using S.DS namespace (which uses ADSI) to the S.SD.Protocol namespace. The only problem is that ADSI handled the conversion of Generalized-Time to a DateTime for me. Now I'm getting back a value of "20070828085401.0Z" for the WhenChanged attribute. DateTime.Parse() will not convert this so is there another way?
The format you are getting is close to the round trip date time pattern ("o") and universal sortable round trip date time pattern ("u") standard date time format strings as described here.
One kludgy solution would be to massage the string you get to fit the pattern and then use the "o" or "u" standard format string with ParseExact.
A better way would be to construct a custom format string that matches the data you are already getting. In the "How Standard Format Strings Work" section of the standard date time format strings page you'll see the full custom formatting strings equivalent to "o" and "u". That should give you a good start.
EDIT: Add code
string format = "yyyyMMddHHmmss.f'Z'";
string target = "20070828085401.0Z";
DateTime d = DateTime.ParseExact(target, format, CultureInfo.InvariantCulture);
In the comments lixonn observes that, using the format string above, ParseExact will not successfully parse a time string like 199412160532-0500.
It also won't parse a number of other valid strings such as times without the trailing 'Zulu' indicator (20070828085401.0); times without a fractional part (20070828085401Z) and times that represent minutes and seconds as a fractional hour (2007082808.90028Z).
The format string can be made slightly more forgiving by replacing the hard-coded 'Z' with the K custom specifier which will accept 'Z', an offset like -0500, and nothing. Whether that additional flexibility is a good thing will depend on your application.
Note that even with the K specifier Lixonn's string won't be parsed successfully since it lacks a fractional part to match the .f component of the format string.
You'll have to use DateTime.ParseExact() specifying the exact format.
You might have to play with the format a little bit but it would be something like this.
DateTime result;
CultureInfo provider = CultureInfo.InvariantCulture;
string format="yyyyMMddhhmmss.0Z";
result = DateTime.ParseExact(dateString, format, provider);
You can use datetime's .strptime().
import datetime
# Since 0Z denotes UTC, you can get rid of it and apply the timezone
# later if you would like
time_string = "20070828085401.0Z".split('.')[0]
time_object = datetime.datetime.strptime(time_string, "%Y%m%d%H%M%S")
time_object should output as datetime.datetime(2007, 8, 28, 8, 54, 1). I believe it will be timezone naive, and equivalent to UTC time.
// WIN32 FILETIME is a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).
// While the unix timestamp represents the seconds since January 1, 1970 (UTC).
private static long Win32FileTimeToUnixTimestamp(long fileTime)
{
//return fileTime / 10000L - 11644473600000L;
return DateTimeOffset.FromFileTime(fileTime).ToUnixTimeSeconds();
}
// The GeneralizedTime follows ASN.1 format, something like: 20190903130100.0Z and 20190903160100.0+0300
private static long GeneralizedTimeToUnixTimestamp(string generalizedTime)
{
var formats = new string[] { "yyyyMMddHHmmss.fZ", "yyyyMMddHHmmss.fzzz" };
return DateTimeOffset.ParseExact(generalizedTime, formats, System.Globalization.CultureInfo.InvariantCulture).ToUnixTimeSeconds();
}