Cá nhân tôi sẽ định dạng nó trong hai phần: phần không sáng/chiều, và sáng/chiều phần với ToLower:
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mm") +
item.PostedOn.ToString("tt").ToLower();
Một tùy chọn khác (mà tôi sẽ điều tra trong một giây) là để lấy DateTimeFormatInfo hiện tại, tạo một bản sao và thiết lập các trình thiết kế am/pm cho phiên bản chữ thường. Sau đó, sử dụng thông tin định dạng đó cho định dạng thông thường. Bạn muốn cache DateTimeFormatInfo, rõ ràng là ...
EDIT: Mặc dù nhận xét của tôi, tôi đã viết bit bộ nhớ đệm anyway. Nó có thể sẽ không được nhanh so với mã trên (vì nó liên quan đến một khóa và một tra cứu từ điển) nhưng nó làm cho mã gọi đơn giản hơn:
string formatted = item.PostedOn.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
GetLowerCaseInfo());
Dưới đây là một chương trình đầy đủ để chứng minh:
using System;
using System.Collections.Generic;
using System.Globalization;
public class Test
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToString("dddd, MMMM d, yyyy a\\t h:mmtt",
GetLowerCaseInfo());
}
private static readonly Dictionary<DateTimeFormatInfo,DateTimeFormatInfo> cache =
new Dictionary<DateTimeFormatInfo,DateTimeFormatInfo>();
private static object cacheLock = new object();
public static DateTimeFormatInfo GetLowerCaseInfo()
{
DateTimeFormatInfo current = CultureInfo.CurrentCulture.DateTimeFormat;
lock (cacheLock)
{
DateTimeFormatInfo ret;
if (!cache.TryGetValue(current, out ret))
{
ret = (DateTimeFormatInfo) current.Clone();
ret.AMDesignator = ret.AMDesignator.ToLower();
ret.PMDesignator = ret.PMDesignator.ToLower();
cache[current] = ret;
}
return ret;
}
}
}
Nguồn
2009-01-31 19:39:40
thêm tại http://stackoverflow.com/questions/448634/how-to-format-a-datetime-like-oct-10-2008-1043am-cst-in-c – tvanfosson