简体   繁体   中英

Parsing custom format to DateTime

I am trying to convert string to DateTime. Code look as follows:

DateTime.Parse("20131101T210705.282Z").ToShortTimeString()

I am getting format exception.

I tried providing following format "yyyyMMddTssmmhh.fffz" but received same exception. Code looked as follows

DateTime dt;
if (DateTime.TryParseExact("20131101T210705.282Z",
                           "yyyyMMddTssmmhh.fffz",
                          new CultureInfo("en-US"),
                          DateTimeStyles.None,
                          out dt))
    return dt.ToShortTimeString();

In this case code doesn't parse the string.

Try this :

 DateTime dt;
    if (DateTime.TryParseExact("20131101T210705.282Z",
                               "yyyyMMddTssmmhh.fffZ",
                              new CultureInfo("en-US"),
                              DateTimeStyles.None,
                              out dt))
        return dt.ToShortDateString() + " " + dt.ToShortTimeString();

This might be one way to parse.

   var timeStamp = "20131101T210705.282Z";
   var datetime = timeStamp.Split(new[] { 'T' ,'.'});
   DateTime dt1;


  if (DateTime.TryParseExact(datetime[0],
                     new string[] { "yyyyMMdd" },
                    new CultureInfo("en-US"),
                    DateTimeStyles.None,
                    out dt1))
  {
    Console.WriteLine(dt1.ToShortDateString());
  }

  DateTime dt2;


  if (DateTime.TryParseExact(datetime[1],
                     new string[] { "ssmmhh" },
                    new CultureInfo("en-US"),
                    DateTimeStyles.None,
                    out dt2))
  {
    Console.WriteLine(dt2.ToShortTimeString());
  }

  Console.WriteLine(dt1.ToShortDateString() + " " + dt2.ToShortTimeString());
  Console.ReadLine();

The format was simply incorrect. The timestamp value given doesn't clearly indicate where the hours are since all values (hours, minutes, and seconds) are less than 24. The following code works correctly.

DateTime.TryParseExact(value,
                       "yyyyMMddTHHmmss.fffZ",
                       CultureInfo.InvariantCulture,
                       DateTimeStyles.None,
                       out dt)

Given this proprietary format, the hours are in 24 hour format and come first. A test from this morning yielded the following value: 20131106T162733.032Z. I am able to test this proprietary format because we work for the same company. :)

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