Convert 20121004 (yyyyMMdd) to a valid date time?

前端 未结 4 1259
被撕碎了的回忆
被撕碎了的回忆 2020-12-25 09:32

I have a string in the following format yyyyMMdd and I am trying to get it to look like this:

yyyy-MM-dd

When I try:



        
4条回答
  •  北海茫月
    2020-12-25 10:15

    Here is an extension method I use.

    /// 
    /// Converts a string to a dateTime with the given format and kind.
    /// 
    /// The date time string.
    /// The date time format.
    /// Kind of the date time.
    /// 
    public static DateTime ToDateTime(this string dateTimeString, string dateTimeFormat, DateTimeKind dateTimeKind)
    {
        if (string.IsNullOrEmpty(dateTimeString))
        {
            return DateTime.MinValue;
        }
    
        DateTime dateTime;
        try
        {
            dateTime = DateTime.SpecifyKind(DateTime.ParseExact(dateTimeString, dateTimeFormat, CultureInfo.InvariantCulture), dateTimeKind);
        }
        catch (FormatException)
        {
            dateTime = DateTime.MinValue;
        }
    
        return dateTime;
    }
    

提交回复
热议问题