Convert weird date format to short DateTime

I have a date string, returned from a ExtJS datetime picker, which 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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.

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.

Method 2

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

Method 3

May be this can help you Click

Method 4

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;

Method 5

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x