怪异的转换日期格式日期时间短 [英] Convert weird date format to short DateTime

查看:173
本文介绍了怪异的转换日期格式日期时间短的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个日期字符串,从ExtJS的日期时间选择器returne,至极看起来是这样的:

I have a date string, returne from a ExtJS datetime picker, wich looks like this :

Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)

在此,我需要有它的格式为:YYYY-MM-DD,使用C#或JavaScript。
我怎么能这样做呢?我已经使用DateTime.Parse尝试,它不能被解析。
任何想法?

From this I would need to have it in this format : YYYY-mm-dd, using C# or JavaScript. How could I do this ? I've tried using DateTime.Parse and it cannot be parsed. Any idea?

感谢您!

推荐答案

您似乎并不计较时间和时区信息,这样你就可以在实际上使用 DateTime.ParseExact 来解析日期。假设月份部分的日子可能只是一个单一的数字(例如:2012-04-01为太阳2012年4月1日),你需要使用的模式是 DDD yyyy年MMM d

You don't seem to care about the time and timezone information so you can in fact use DateTime.ParseExact to parse the date. Assuming that the day of month part may be just a single digit (e.g. 2012-04-01 is Sun Apr 1 2012) the pattern you need to use is ddd MMM d yyyy.

在最困难的部分是真正的切碎的时间和时区的一部分。如果月的某一天是一个数字,你必须采取长14的子串;否则长度15.这是一种方式来获得一个字符串中第四空格字符的索引:

The "hardest" part is really chopping of the time and timezone part. If the day of month is a single digit you have to take of substring of length 14; otherwise of length 15. Here is a way to get the index of the 4th space character in a string:

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);

这可以使用任何你需要的格式和文化被格式化回字符串。

This can be formatted back into a string using whatever format and culture you need.

这篇关于怪异的转换日期格式日期时间短的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆