What is wrong with this TimeSpan.ParseExact line? - c#

I am receiving a FormatError exception from this call to TimeSpan.ParseExact, but the MSDN documentation that I am reading says that this format should be correct:
TimeSpan timeSpan = TimeSpan.ParseExact("172100", "HHmmss", CultureInfo.InvariantCulture);
Can someone please tell me why this is not working? I am doing almost exactly the same thing with a call to DateTime.ParseExact and this works fine:
DateTime datetTime = DateTime.ParseExact("090820", "yyMMdd", CultureInfo.InvariantCulture);

TimeSpan does not use the same formatting rules as DateTime.
You want hhmmss, not HHmmss.
You're looking at the wrong page in MSDN - you want something like:
http://msdn.microsoft.com/en-us/library/se73z7b9.aspx

With ref to this more accurate documentation: http://msdn.microsoft.com/en-us/library/ee372287.aspx
You need to use hh for hours, not HH.

As per Custom TimeSpan Format Strings, hours are represented by "h" rather than "H".
So this works fine:
TimeSpan timeSpan = TimeSpan.ParseExact("172100", "hhmmss",
CultureInfo.InvariantCulture);
The documentation you linked to is for custom date and time format strings, which aren't the same. They're for DateTime.ParseExact etc; the documentation I linked to is for TimeSpan.ParseExact etc.

Parse the string to a DateTime value, then subtract it's Date value to get the time as a TimeSpan:
DateTime t = DateTime.ParseExact("172100", "HHmmss", CultureInfo.InvariantCulture);
TimeSpan time = t - t.Date;

You are try to use DateTime format strings to parse a TimeSpan. TimeSpan has its own (slightly different) format strings. See MSDN for a complete listing: Custom TimeSpan Format Strings
In particular, change HH to hh. This will give you:
TimeSpan timeSpan = TimeSpan.ParseExact("172100",
"hhmmss", // Note this parameter
CultureInfo.InvariantCulture);

Related

convert resulting string datetime to dateTime value

i am fetching datetime value through xml like:
string time = "20150605020247+0000"
I want to convert into datetime value. I tried with DateTime.Parse, ParseExact, Convert.ToDateTime. It's not working, it's returning the error:
string was not recognised as valid datetime
You should use DateTime.ParseExact like this
DateTime theTime = DateTime.ParseExact(time, "ddMMyyyyHHmmss+ffff,CultureInfo.InvariantCulture);
You should be able to use DateTime.ParseExact, since you know the exact format of the string. If we assume it's year, month, day, hour, minute, second, and offset, then you can do something like:
var result = DateTime.ParseExact("20150605020247+0000", "yyyyMMddHHmmsszzz",
CultureInfo.InvariantCulture);
You need to use exact format specifier in your ParseExact method.
DateTime.ParseExact("20150605020247+0000", "yyyyMMddHHmmsszzz", System.Globalization.CultureInfo.InvariantCulture);
Fiddle: https://dotnetfiddle.net/cQJ9hN
EDIT:
Please check the standard DateTime formats used in .NET world: https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings plus check the source of your data how exactly are the string dates produced.
However most likely the '+####' part of your string is the local date UTC offset, not the fractions part of the time (as other answers suggest). So parsing the date by using the "yyyyMMddhhmmssffff" would produce wrong results.

c# parse date time with timezone

How can we parse date time with time zone.
<TIMESTAMP_UTC>20180523160000</TIMESTAMP_UTC>
<TIMEZONE>UTC+8</TIMEZONE>
this should convert as in 2018-05-24 00:00:00.
I tried couple of things but could not succeed.
I tried the below command but it throws an error.
DateTime.ParseExact("20180523160000+08:00", "yyyyMMddHHmmssZhhmm", System.Globalization.CultureInfo.InvariantCulture)
Do you know how we can parse this with DateTime Parse methods.
You need to use DateTimeOffset.ParseExact
var date = DateTimeOffset.ParseExact("20180523160000+08:00", "yyyyMMddHHmmsszzz", CultureInfo.InvariantCulture);
Try using DateTimeOffset.Parse() instead of DateTime.Parse() as DateTimeOffset stores timezone info.
You can refer to the following MSDN link for more details:
https://msdn.microsoft.com/en-us/library/bb351654(v=vs.110).aspx
You could invert the sign of your timezone and then parse it with
var dateTime = DateTime.ParseExact(
"20180523160000UTC-8",
"yyyyMMddHHmmssUTCz",
CultureInfo.InvariantCulture);
But if this is a good approach is probably questionable.

DateTime ParseExact not working when changing time

I'm having trouble figuring out why my date is parsed correctly until I change the time of the date passed into the parse method.
var parsedDate = DateTime.ParseExact("2016-02-05T07:00:00+00:00", "yyyy-MM-ddThh:mm:ss+00:00", CultureInfo.InvariantCulture);
dateValueToTryParse = parsedDate.ToString("dd/MM/yyyy");
The required result is outputted and I do get 05/02/2016. However, if I change the string passed in to:
2016-02-19T23:59:00+00:00
The output of dateValueToTryParse remains the same and it is not parsed correctly. Am I doing anything particularly wrong with my parsing? I'm confused as the format seems to be exactly the same?
You need to change your incoming format to yyyy-MM-ddTHH:mm:ss+00:00.
The difference is HH. Capital H means 24 hour clock or "military time".
Otherwise, it is trying to parse hour 23 which doesn't exist.
See here for more detailed information on other formats: https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx
Changing hh to HH specifier can solve your problem but since your string has an UTC offset value, I would prefer to parse it to DateTimeOffset instead of DateTime for consistency.
var dto = DateTimeOffset.ParseExact("2016-02-05T23:00:00+00:00",
"yyyy-MM-ddTHH:mm:sszzz",
CultureInfo.InvariantCulture);
Now, you have a DateTimeOffset as {05.02.2016 23:00:00 +00:00} and you can use it's .DateTime property to get the DateTime value represented by it.
var dateValueToTryParse = dto.DateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture);
This will generate 05/02/2016 as a result.

Why won't this string be converted to DateTime?

2/22/2012 3:30:00
Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()?
I would personally avoid using Convert.ToDateTime. I generally prefer1 to use DateTime.TryParseExact, specifying the culture and format string you expect - assuming you have an expected format, of course. If you don't, you have to ask yourself bigger questions.
For example:
DateTime value;
if (DateTime.TryParseExact(text, "M/d/yyyy H:mm:ss",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out value))
{
Console.WriteLine("Parsed to {0}", value);
}
else
{
Console.WriteLine("Failed to parse");
}
That's a slightly odd format to start with - normally a 24-hour format would include a leading 0 for the hour, and a 12-hour format would include an am/pm designator.
1 Well, I prefer to use Noda Time, but that's a different matter...
Surely that is an acceptable format to be converted to DateTime using Convert.ToDateTime()?
Surely not. That would be true for some locales but for example I have a fr-FR locale and this is an invalid date. There are no 22 months in the year. Make sure you specify the format when parsing the date. You could use the TryParseExact method for this.
If you got the Information about Year, Month, etc. separately as Integers I would rather use the Constructor of DateTime.
DateTime myDateTime = new DateTime(year, month, day, hour, minute, second);
Usually nothing can go wrong with this...
It should be able to if you supply an IFormatProvider which specifies the culture (e.g. en-US in that case).
var date = Convert.ToDateTime("2/22/2012 3:30:00", CultureInfo.GetCultureInfo("en-US"));
Here is an example on how to use Convert.ToDateTime() which will help you to understand it :
Convert.ToDateTime example
Or You can try by following this example :
Convert String to DateTime
This works just fine for me:
DateTime dt = Convert.ToDateTime("2/22/2012 3:30:00");
Console.WriteLine(dt.ToShortDateString());
Console.WriteLine(dt.ToShortTimeString());
Of course I am not paying attention to localization like Darin suggests

Help converting a string date to a DateTime

I'm using the Ajax control toolkit calendar extender on a textbox with a submit button. Simple.
The debugger shows that the text is properly being transferred to calling method, but this line of conversion code converts textbox text to 1/1/0001 12:00:00 AM. The text box date is this: 4/15/2011
DateTime txtMyDate = Convert.ToDateTime(txtDate.Text);
What am I doing wrong?
You should use the DateTime.Parse() method:
DateTime txtMyDate = DateTime.Parse(txtDate.Text);
As mentioned you can also use DateTime.ParseExact() using a similar syntax as shown:
DateTime txtMyDate = DateTime.ParseExact(txtDate.Text,
[string format],
[IFormatProvider provider]);
Parse vs ParseExact:
Parse() - assumes the data is valid and does its best to fit it into the type, forcing things that seem vaguely ridiculous when a developer has a chance to invoke common sense.
ParseExact() - only allows the exact format specified and will throw on any variation.
Source on Parse vs ParseExact
There are many ways to convert text to a DateTime, try this one:
DateTime txtMyDate =
DateTime.ParseExact(txtDate.Text, "M/d/yyyy", CultureInfo.InvariantCulture);
Edit: forgot the culture info argument
Use DateTime.ParseExact to extract your date value from a formated date string:
DateTime dateValue =
DateTime.ParseExact(stringDateValue, "M/d/yyyy",
CultureInfo.InvariantCulture);
Try
DateTime instance = DateTime.Parse( txtDate.Text ) ;
which is [somewhat] flexible about what it will accept. Alternatively, DateTime.ParseExact() will give you move control over the conversion.

Categories

Resources