[英]Convert a short DateTime string with date and time to DateTime
[英]Convert weird date format to short DateTime
我有一個日期字符串,從ExtJS datetime選擇器返回,看起來像這樣:
Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)
由此,我需要使用C#或JavaScript格式:YYYY-mm-dd。 我該怎么辦? 我嘗試使用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中
new Date("Wed Apr 25 2012 00:00:00 GMT+0300 (GTB Daylight Time)")
將給您一個日期對象。 然后,您可以通過選擇(UTC)年,月和日,將其格式化為日期格式(最好是ISO8601,或者使用.getTime()從epoc到毫秒)。
嘗試使用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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.