简体   繁体   中英

Convert weird date format to short DateTime

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)

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?

Thank you!

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 (eg 2012-04-01 is Sun Apr 1 2012 ) the pattern you need to use is ddd MMM d yyyy .

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

You can then parse the date into a 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.

In .NET, where you have a string representation of a date that has a guaranteed format, you can use DateTime.ParseExact to parse it:

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

也许这可以帮助您单击

In JavaScript

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

Will give you a date object. You can then format it to your date format (or preferably ISO8601, or milliseconds from the epoc using .getTime()) by picking out the (UTC) year, month and day

try this using 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM