将奇怪的日期格式转换为短日期时间
Convert weird date format to short DateTime
我有一个日期字符串,从 ExtJS 日期时间选择器返回,如下所示:
Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)
由此,我需要以这种格式使用它:YYYY-mm-dd,使用 C# 或 JavaScript。我该怎么做?我尝试使用DateTime.Parse,但它无法解析。知道吗?
您似乎并不关心时间和时区信息,因此实际上您可以使用DateTime.ParseExact
来解析日期。假设月份中的日期部分可能只是一个数字(例如 2012-04-01 是 Sun Apr 1 2012
),您需要使用的模式是 ddd MMM d yyyy
。
"最难"的部分实际上是时间和时区部分的切碎。如果月份中的某天是一个数字,则必须取长度为 14 的子字符串;否则长度为 15。这是一种获取字符串中第 4 个空格字符的索引的方法:
var str = "Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)";
var index = -1;
for (var i = 0; i < 4; i += 1)
index = str.IndexOf(' ', index + 1);
然后,您可以将日期解析为DateTime
:
var date = DateTime
.ParseExact(str.Substring(0, index), "ddd MMM d yyyy", CultureInfo.InvariantCulture);
可以使用所需的任何格式和区域性将其格式化为字符串。
在 .NET 中,具有具有保证格式的日期的字符串表示形式,可以使用 DateTime.ParseExact
来分析它:
var input = "Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)"
.Substring(0, 15);
var format = "ddd MMM dd YYYY";
var date = DateTime.ParseExact(input, format, CultureInfo.InvariantCulture);
// Now date is a DateTime holding the date
var output = date.ToString("yyyy-MM-dd");
// Now output is 2012-04-25
也许这可以帮助你点击
使用Javascript尝试一下。
var d = new Date('Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)');
var curr_day = d.getDate();
var curr_month = ('0'+(d.getMonth()+1)).slice(-2)
var curr_year = d.getFullYear();
var new_date = curr_year+"-"+curr_month+"-"+curr_day;
在 JavaScript 中
new Date("Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)")
会给你一个日期对象。然后,您可以通过选择 (UTC) 年、月和日来将其格式化为日期格式(或者最好是使用 .getTime() 从 epoc 中ISO8601或毫秒)
相关文章:
- 更改angularjs中的日期-时间格式
- 将日期时间作为 JSON 发送将无法在我的视图中正确显示
- 将日期时间从json转换为可读格式
- 使用时刻.js从日期时间中提取时间
- 两个日期时间选择器
- Javascript:如何在onChange事件期间更改日期时间值
- .Net webApi ISO日期时间和IE8
- Javascript-如何使用bootstrap日期时间选择器自动计算两个时间输入之间的差异
- 转换日期时间格式
- 在JavaScript中转换日期/时间格式
- JavaScript JSON关联对象键和值都作为日期时间戳
- 将日期时间javascript绑定到表列
- 将JS日期解析为C#日期时间
- 使用JavaScript将客户端日期/时间字符串转换为JSON日期/时间串
- 从javascript数组获取php的日期时间
- 格式化momentjs日期时间
- 这个正则表达式的日期/时间有什么问题
- Mongoose查询在两个日期时间之间提取数据
- 当转换为Python日期时间时,Node的时间戳落后3分钟
- 自定义angularjs过滤器日期时间格式额外字符