将字符串从一种日期格式转换为另一种日期格式
Convert string from one date format to another
我正在尝试将 2014-12-25
(yyyy-mm-dd) 转换为 December 25, 2014
。执行此操作的最佳做法是什么?我目前将它存储在一个变量中,因为他们从日期选择器中选择日期,但我在页面的其他地方显示该值并希望它以上述格式显示。
代码:
myLabel.Text = "Period: " + FromDate + " to " + ToDate;
开始日期和结束日期是保存日期选择器中日期的两个变量。我需要帮助将其转换为 December 25, 2014
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");
myLabel.Text = "Period: " + FromDate.ToString("MMMM dd, yyyy") + " to " + ToDate.ToString("MMMM dd, yyyy");
thisDate1.ToString("MMMM dd, yyyy")
编辑:
因为你的变量是字符串:
DateTime.ParseExact(stringDate, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MMMM dd, yyyy");
这会让您将格式从字符串日期时间转换为您想要的格式。
如果字符串变量中有“2014-12-25”,您应该首先解析它并将其转换为 DateTime
var dt = DateTime.ParseExact(FromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("MMMM dd, yyyy"));
但是如果您的 DateTime
变量中已经有“2014-12-25”,那么这只是一个格式问题。只需使用
Console.WriteLine(FromDate.ToString("MMMM dd, yyyy"));
我正在尝试将 2014-12-25
(yyyy-mm-dd) 转换为 December 25, 2014
。执行此操作的最佳做法是什么?我目前将它存储在一个变量中,因为他们从日期选择器中选择日期,但我在页面的其他地方显示该值并希望它以上述格式显示。
代码:
myLabel.Text = "Period: " + FromDate + " to " + ToDate;
开始日期和结束日期是保存日期选择器中日期的两个变量。我需要帮助将其转换为 December 25, 2014
Console.WriteLine("Today is " + thisDate1.ToString("MMMM dd, yyyy") + ".");
myLabel.Text = "Period: " + FromDate.ToString("MMMM dd, yyyy") + " to " + ToDate.ToString("MMMM dd, yyyy");
thisDate1.ToString("MMMM dd, yyyy")
编辑:
因为你的变量是字符串:
DateTime.ParseExact(stringDate, "yyyy-MM-dd", CultureInfo.InvariantCulture).ToString("MMMM dd, yyyy");
这会让您将格式从字符串日期时间转换为您想要的格式。
如果字符串变量中有“2014-12-25”,您应该首先解析它并将其转换为 DateTime
var dt = DateTime.ParseExact(FromDate, "yyyy-MM-dd", CultureInfo.InvariantCulture);
Console.WriteLine(dt.ToString("MMMM dd, yyyy"));
但是如果您的 DateTime
变量中已经有“2014-12-25”,那么这只是一个格式问题。只需使用
Console.WriteLine(FromDate.ToString("MMMM dd, yyyy"));