Get AM/PM for a date time in lowercase using only a datetime format

前端 未结 5 1832
野趣味
野趣味 2020-12-30 18:36

I\'m to get a custom DateTime format including the AM/PM designator, but I want the \"AM\" or \"PM\" to be lowercase without making the rest of of the characters lo

5条回答
  •  清歌不尽
    2020-12-30 19:16

    You could split the format string into two parts, and then lowercase the AM/PM part, like so:

    DateTime now = DateTime.Now;
    string nowString = now.ToString("ffffdd, MMMM d, yyyy a\\t h:mm");
    nowString = nowString + now.ToString("tt").ToLower();
    

    However, I think the more elegant solution is to use a DateTimeFormatInfo instance that you construct and replace the AMDesignator and PMDesignator properties with "am" and "pm" respectively:

    DateTimeFormatInfo fi = new DateTimeFormatInfo();
    
    fi.AMDesignator = "am";
    fi.PMDesignator = "pm";
    
    string nowString = now.ToString("ffffdd, MMMM d, yyyy a\\t h:mmtt", fi);
    

    You can use the DateTimeFormatInfo instance to customize many other aspects of transforming a DateTime to a string.

提交回复
热议问题