好的,所以我有一个以英国格式(dd / mm / yy)存储的日期,我需要在用户可能的任何地方显示。
问题是这个日期可以是000000(00/00/2000);所以我不能直接将它转换为DateTime,因为DateTime不支持0或0天的值。
到目前为止,我有这个:
int dateInt = ddmmyy;
var year = (dateInt % 100) + 2000;
var month = (dateInt / 100) % 100;
var day = (dateInt / 100000);
var result = new DateTime(year, month, day); //2014/00/00 at this point, so breaks.
var resultStr = result.ToString(CultureInfo.InvariantCulture);
return resultStr;
最初添加0值支持的正确方法是什么?我尝试在转换为DateTime之前将0更改为1,运行转换然后再次替换为0;但由于文化变异,我认为这种方法无法支持其他文化,这就是开始转化的目的。
有什么想法吗?我猜这是一个常见的问题。
答案 0 :(得分:1)
这是你需要的吗?
using System;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
int[] savedDates = new int[] { 000000, 010000, 000013 };
foreach (var item in savedDates)
{
DateTime date = ConvertToDate(item);
Console.WriteLine(item.ToString("D6") + " => " + date.ToShortDateString());
}
Console.ReadLine();
}
private static DateTime ConvertToDate(int item)
{
string temp = item.ToString("D6");
int day = int.Parse(temp.Substring(0, 2));
int month = int.Parse(temp.Substring(2, 2));
int year = int.Parse(temp.Substring(4, 2));
if (day == 0)
day = 1;
if (month == 0)
month = 1;
year += 2000;
return new DateTime(year, month, day);
}
}
}
答案 1 :(得分:0)
我不会存储这样的日期,因为.NET框架已经提供了这样做的方法。
存储日期的最佳方法是使用Culture.InvariantCulture
进行字符串转换,然后根据需要转换为本地文化以供显示。 DateTime
本身与文化无关,因此很容易在文化之间进行转换。