Converting a String to DateTime

后端 未结 17 2598
南方客
南方客 2020-11-21 06:12

How do you convert a string such as 2009-05-08 14:40:52,531 into a DateTime?

17条回答
  •  时光说笑
    2020-11-21 06:46

    Put this code in a static class> public static class ClassName{ }

    public static DateTime ToDateTime(this string datetime, char dateSpliter = '-', char timeSpliter = ':', char millisecondSpliter = ',')
    {
       try
       {
          datetime = datetime.Trim();
          datetime = datetime.Replace("  ", " ");
          string[] body = datetime.Split(' ');
          string[] date = body[0].Split(dateSpliter);
          int year = date[0].ToInt();
          int month = date[1].ToInt();
          int day = date[2].ToInt();
          int hour = 0, minute = 0, second = 0, millisecond = 0;
          if (body.Length == 2)
          {
             string[] tpart = body[1].Split(millisecondSpliter);
             string[] time = tpart[0].Split(timeSpliter);
             hour = time[0].ToInt();
             minute = time[1].ToInt();
             if (time.Length == 3) second = time[2].ToInt();
             if (tpart.Length == 2) millisecond = tpart[1].ToInt();
          }
          return new DateTime(year, month, day, hour, minute, second, millisecond);
       }
       catch
       {
          return new DateTime();
       }
    }
    

    In this way, you can use

    string datetime = "2009-05-08 14:40:52,531";
    DateTime dt0 = datetime.TToDateTime();
    
    DateTime dt1 = "2009-05-08 14:40:52,531".ToDateTime();
    DateTime dt5 = "2009-05-08".ToDateTime();
    DateTime dt2 = "2009/05/08 14:40:52".ToDateTime('/');
    DateTime dt3 = "2009/05/08 14.40".ToDateTime('/', '.');
    DateTime dt4 = "2009-05-08 14:40-531".ToDateTime('-', ':', '-');
    

提交回复
热议问题