Chuyển từ String sang DateTime:
Giả sử bạn có 1 chuỗi: Mon 16 Jun 8:30 AM 2008 và muốn chuyển sang DateTime, bạn dùng:var tg = DateTime.Parse(dateString);//Error: String was not recognized as a valid DateTime.Trong trường hợp này, bạn phải chỉ ra đúng định dạng ngày giờ phút giây bạn đang xài cho trình biên dịch hiểu.
using System;
using System.Globalization;
class Program
{
static void Main()
{
string dateString = "Mon 16 Jun 8:30 AM 2008"; // Modified from MSDN
string format = "ddd dd MMM h:mm tt yyyy";
DateTime dateTime = DateTime.ParseExact(dateString, format,
CultureInfo.InvariantCulture);
Console.WriteLine(dateTime);
Console.WriteLine(dateTime);
}
}
Output: 6/16/2008 8:30:00 AMCustom DateTime Formatting:
y (year),
M (month), d (day), h (hour 12),
H (hour 24), m (minute), s (second),
f (second fraction), F (second fraction, trailing
zeroes are trimmed), t (P.M or A.M) and z
(time zone).Bạn có thể tham khảo cách định dạng DateTime tại MSDN
Tips: Muốn tùy chỉnh chuỗi DateTime khi xuất ra
Console.WriteLine("{0:hh:mm:ss.fff}", dateTime);//08:30:00.000
Nhận xét
Đăng nhận xét