convert resulting string datetime to dateTime value - c#

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.

Related

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.

Parse a UTC date string to date in C#

Simple question, I have this string:
string dateString = "7/12/2014 4:42:00 PM";
This is a date string and it's in the UTC timezone.
I need to convert it to a date, so I'm doing the following:
DateTimeOffset dateOffset;
DateTimeOffset.TryParse(dateString, out dateOffset);
DateTime date = dateOffset.UtcDateTime;
The problem:
When I'm parsing the string to date, the code is considering that the dateString is in the Local Timezone of the PC (+3 GMT), and not in the UTC timezone.
So I am getting the following the dateOffset = {7/12/2014 4:42:00 PM +03:00} and thus date = {7/12/2014 1:42:00 PM}
how can I tell him that the date string provided is in the UTC format and not in the local timezone format?
Thanks
how can I tell him that the date string provided is in the UTC format and not in the local timezone format?
Specify a DateTimeStyles value of AssumeUniversal in the call. That tells the parsing code what to do. For example:
// null here means the thread's current culture - adjust it accordingly.
if (DateTimeOffset.TryParse(dateString, null, DateTimeStyles.AssumeUniversal,
out dateOffset))
{
// Valid
}
You should always use the result of TryParse to tell whether or not it's successfully parsed.
If you know the format and the specific culture, I'd personally use DateTimeOffset.TryParseExact. (Well, to be honest I'd use my Noda Time project to start with, but that's a different matter.)
There is another overload of DateTimeOffset.TryParse
DateTimeOffset.TryParse Method (String, IFormatProvider, DateTimeStyles, DateTimeOffset)
which allows you specify DateTimeStyles. One of the DateTimeStyles is AssumeUniversal, which is what you're looking for:
If no time zone is specified in the parsed string, the string is
assumed to denote a UTC. This value cannot be used with AssumeLocal or
RoundtripKind.
Don't know how .Net API provides, but I guess you could probably use ISO8601 format to indicate a UTC timezone before parsing, i.e, first translate 7/12/2014 4:42:00 PM into something 2014-07-02T16:42:00Z, then use try parse using DateTimeOffset

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

What is wrong with this TimeSpan.ParseExact line?

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);

Categories

Resources