我会直接进入它,我的一个小小的烦恼正在与DateTime
合作cultures
{{1}和全球化。
在我的应用程序中,这是在国际层面上使用的,我试图找出构建一个能够处理所有格式的函数的最佳方法,而不管格式是否传递。
我想目前我还不完全确定,为什么我有一个特定的格式不能解析为通过客户端传递的日期。
这暂时都在测试中,但哔哔声中的痛苦从未如此......
目前,我正在尝试转换timezones
日期以及附加的en_gb
代码段。
standard ISO format
所以,如果我可能会问,为什么string[] formats = {
"d/M/yyyy h:mm:ss tt",
"d/M/yyyy h:mm tt",
"dd/MM/yyyy hh:mm:ss",
"d/M/yyyy h:mm:ss",
"d/M/yyyy hh:mm tt",
"d/M/yyyy hh tt",
"d/M/yyyy h:mm",
"d/M/yyyy h:mm",
"dd/MM/yyyy hh:mm",
"dd/m/yyyy hh:mm",
"yyyy-MM-dd'T'HH:mm:sszzz",
"dd/MM/yyyy hh:mm:ss UTC"
};
if (DateTime.TryParseExact(val, formats,
CultureInfo.CurrentCulture,
DateTimeStyles.AllowWhiteSpaces, out dt))
{
return dt;
}
解析但13/06/2017 10:25:00 UTC
失败(返回false)。
我觉得我可能已经盯着这个太久了。
真的很欣赏正确方向的推动......
答案 0 :(得分:1)
您的问题是您在使用h
或hh
时匹配时间为12小时(即接受1-12或01-12)。如果您要将"dd/MM/yyyy HH:mm:ss UTC"
添加到格式列表中,则可以匹配27/06/2017 16:11:00 UTC
。一般来说,我怀疑没有tt
说明符的任何内容可能想要H
/ HH
而不是h
/ hh
,但我会留给您决定确定你想要什么。
答案 1 :(得分:0)
检查一下,
static void FormatDate(string strInputDateTimeValue)
{
int day = 0, month = 0, year = 0, hours = 0, minutes = 0, seconds = 0, milliSeconds = 0, dateTimeKind = 0;
List<string> lstSplittedInputDateTime = (from data in strInputDateTimeValue.Split(' ').ToList() where !string.IsNullOrEmpty(data) select data).ToList();
if (lstSplittedInputDateTime != null)
{
string strDate = lstSplittedInputDateTime[0];//Fetching Only Date Part: Considering date format will be mm/DD/yyyy
if (!string.IsNullOrEmpty(strDate))
{
month = Convert.ToInt32(strDate.Split('/').ToList()[1]);//Fetch Month
day = Convert.ToInt32(strDate.Split('/').ToList()[0]);//Fetch Day
year = Convert.ToInt32(strDate.Split('/').ToList()[2]);//Fetch Year
}
string strTime = lstSplittedInputDateTime[1];//Fetching Only Time Part
if (strTime != null)
{
hours = Convert.ToInt32(strTime.Split(':').ToList()[0]);//Fetch Hours
minutes = Convert.ToInt32(strTime.Split(':').ToList()[1]);//Fetch Minutes
seconds = Convert.ToInt32(strTime.Split(':').ToList()[2]);//Fetch Seconds
milliSeconds = Convert.ToInt32(strTime.Split(':').ToList()[3]);//Fetch MilliSeconds
}
string strDateTimeKind = lstSplittedInputDateTime[2];//Fetching DateTimeKind
if (strDateTimeKind != null)
{
if (strDateTimeKind.ToLower() == "utc")
dateTimeKind = (int)System.DateTimeKind.Utc;
else if (strDateTimeKind.ToLower() == "Local")
dateTimeKind = (int)System.DateTimeKind.Local;
else
dateTimeKind = (int)System.DateTimeKind.Utc;
}
}
DateTime dtFormattedDate = new DateTime(year, month, day, hours, minutes, seconds, (DateTimeKind)dateTimeKind);
Console.WriteLine("Local: {0}", TimeZoneInfo.ConvertTime(dtFormattedDate, TimeZoneInfo.Local).ToString());
Console.WriteLine("UTC: {0}", TimeZoneInfo.ConvertTime(dtFormattedDate, TimeZoneInfo.Utc).ToString());
}
public void Run()
{
FormatDate("27/06/2017 16:11:00 UTC");
Console.ReadLine();
}