简体   繁体   中英

Converting a String into a Valid DateTime Format

I have two Timestamps that are saved to and read from two XML files.
Currently I am reading the timestamps from the xml files in a WCF Service method, so they are coming in as Strings , but I need them to be converted into DateTime so they can be compared.

The obvious Convert.ToDateTime(TimeStampString) renders this error at Runtime -

String was not recognized as a valid DateTime

As does

DateTime.ParseExact(TimeStampString, "mm/dd/yyyy hh:MM:ss", CultureInfo.InvariantCulture);

Both Timestamps are in the correct format for DateTime ( mm/dd/yyyy hh:MM:ss ).

I've even tried splitting the timstamp strings into String[] and assembling my own DateTime object by hand, and I still received the error.

Is this a format issue?
How can I make my String a valid DateTime?

It's a format issue

mm/dd/yy hh:MM:ss

should be

MM/dd/yyyy hh:mm:ss

(basically, swap the upper case MM in the date & the lowercase mm in the time)

I resolved the issue by removing any attempts to alter the format from US, so Strings came in with US format - then used an IFormatProvider to alter the format at conversion time.

IFormatProvider localFormat = new System.Globalization.CultureInfo("fr-FR", true);
DateTime ContentLastUpdatedTime = DateTime.Parse(ContentLastUpdatedStamp, localFormat , System.Globalization.DateTimeStyles.AssumeLocal);
DateTime ContentLastGrabbedTime = DateTime.Parse(LastGrabbedTimeStamp, localFormat , System.Globalization.DateTimeStyles.AssumeLocal);

You need to use

DateTime.ParseExact(TimeStampString, "MM/dd/yyyy hh:mm:ss", CultureInfo.InvariantCulture);

instead of

DateTime.ParseExact(TimeStampString, "mm/dd/yyyy hh:MM:ss", CultureInfo.InvariantCulture);

The issue is lower case mm which is used for minutes, You need MM upper case MM , plus your date is in 24 hours format, and you need upper case HH for hour part , so your format should be:

MM/dd/yyyy HH:mm:ss

(considering you have yyyy in your original code based on your comment )

See: Custom Date and Time Format Strings

Here you go

var dtedatetime = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz");


DateTimeOffset dto;
bool bIsParsed = DateTimeOffset.TryParseExact(dtedatetime , "yyyy'-'MM'-'dd'T'HH':'mm':'sszzz",
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    DateTimeStyles.AdjustToUniversal, out dto);

    var result = dto.DateTime;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM