Convert string to specific DateTime format

前端 未结 5 1580
既然无缘
既然无缘 2021-01-07 01:17

I\'ve been googling for a while now and for the life of me can\'t seem to find a solution. I thought this would be easy but it\'s taking too long and am turning to stackover

5条回答
  •  既然无缘
    2021-01-07 02:18

    If you have a string, you must first guarantee that it can indeed be converted to a datetime.
    So first, do so. Once you have a datetime, store it in a database as is, you do not need to be copncerned about format, (as others have said here).

    and then, if you need to, reformat it to a different representation only if you need to display it somewhere..

    string s = "21 June 2010 09:23:56";
    DateTime dt;
    if (DateTime.TryParse(s, out dt))
       // dit is a valid datetime, storeit or whatever
    else
       throw ApplicationException(
            "{0} is not a valid datetime.", s);
    //  --  and now you can redisplay dt any way you want -----
    debug.Print(s.ToString("d MMM yyyy");
    debug.Print(s.ToString("HH:mm:ss");
    debug.Print(s.ToString("ffffdd, d MMM yy");
    debug.Print(s.ToString("MMM d, yyyy");
    debug.Print(s.ToString("HH:mm:ss ffffdd");
    

    // etc...

提交回复
热议问题