AnApprentice
AnApprentice

Reputation: 110970

javaScript, jQuery - how to convert a timestamp to a date format like Jan 2, or Jan 26?

Given a string like:

Sun Feb 06 2011 12:49:55 GMT-0800 (PST)

How can you convert that to:

Feb 6

And / Or

Sun Jan 26 2011 12:49:55 GMT-0800 (PST)
to: Jan 26

Any ideas?

Upvotes: 2

Views: 4907

Answers (3)

Eric Fortis
Eric Fortis

Reputation: 17350

Another way can be

var text = 'Sun Feb 06 2011 12:49:55 GMT-0800 (PST)';

var pat=/\w{3}\s\d{2}/;
text = text.substring(4);
text = text.match(pat);

alert(text);

//output: Feb 06

Upvotes: 0

David Tang
David Tang

Reputation: 93674

There aren't any built-in formatting functions to use here, you just have to use the Date methods to build the string:

var months = [
    'Jan', 'Feb', 'Mar', 'Apr',
    'May', 'Jun', 'Jul', 'Aug',
    'Sept', 'Oct', 'Nov', 'Dec'
];

var d = new Date();
// Or,
var d = new Date('Sun Feb 06 2011 12:49:55 GMT-0800 (PST)');

alert(months[d.getMonth()] + ' ' + d.getDate());

Or, if that string will always stay in that format, you can simply extract the relevant parts without converting it to a date object first:

var str = 'Sun Feb 06 2011 12:49:55 GMT-0800 (PST)';
var components = str.split(' ').slice(1, 3);
components[1].replace(/^0/, '');
alert(components.join(' '));

Upvotes: 2

amphetamachine
amphetamachine

Reputation: 30595

I think this question could help you out somewhat.

strptime is a very useful POSIX function for interpreting human-readable dates.

Other than that, I'm pretty sure the Date object can parse human-readable dates:

var myDate = new Date(dateString);
var tm = {
    tm_sec:  myDate.getSeconds(),
    tm_min:  myDate.getMinutes(),
    tm_hour: myDate.getHours(),
    tm_mday: myDate.getDate(),
    tm_mon:  myDate.getMonth(),
    tm_year: myDate.getFullYear().toString().substring(2),
    tm_wday: myDate.getDay()
};

Upvotes: 1

Related Questions