将日期时间字符串转换为ddd MMM dd HH:mm:ss'EST'yyyy格式? [英] Converting DateTime string in ddd MMM dd HH:mm:ss 'EST' yyyy format?
问题描述
在我看来,我正在返回一个在控制器中被转换为DateTime的字符串。字符串格式是ddd MMM dd HH:mm:ss'EST'yyyy。
In my view I am returning a string that is being converted into a DateTime in my controller. The string format is "ddd MMM dd HH:mm:ss 'EST' yyyy".
我正在成功转换它:
var startDate = DateTime.ParseExact(_startDate, "ddd MMM dd HH:mm:ss 'EST' yyyy", CultureInfo.InvariantCulture);
model.StartDate = Convert.ToDateTime(startDate);
问题是时区可能是什么。我该怎么办?不一定会是'EST'
。如果是EDT,例如它会抛出异常。
The problem is that the time zones could be anything. how can I account for this? Its not always the case it will be 'EST'
. If it is EDT for example it will throw an exception.
示例输入字符串为: Mon Feb 20 00:00:00 EST 2017
编辑:也可以是格式 ddd MMM d HH:mm:ss'EST'yyyy
这只会在美国和加拿大使用时区。
It also can be the format ddd MMM d HH:mm:ss 'EST' yyyy
This will only be used in USA and Canada Time zones.
推荐答案
在我的控制器中,我现在进行以下操作。
In my controller I do the following now.
var startDateTZ = _startDate.Substring(20, 4);
if (startDateTZ[3] == ' ')
{
startDateTZ = _startDate.Substring(20, 3);
}
if (startDateTZ.Length > 3)
{
if (startDateTZ[3] == '0')
{
startDateTZ = _startDate.Substring(19, 4);
}
if (startDateTZ[3] == '2')
{
startDateTZ = _startDate.Substring(19, 3);
}
}
var startDate = new DateTime();
if (_startDate[9] != ' ')
{
startDate = DateTime.ParseExact(_startDate, "ddd MMM dd HH:mm:ss '" + startDateTZ + "' yyyy", CultureInfo.InvariantCulture);
}
else
{
startDate = DateTime.ParseExact(_startDate, "ddd MMM d HH:mm:ss '" + startDateTZ + "' yyyy", CultureInfo.InvariantCulture);
}
model.StartDate = startDate;
这篇关于将日期时间字符串转换为ddd MMM dd HH:mm:ss'EST'yyyy格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!