开发者

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

开发者 https://www.devze.com 2023-02-08 18:15 出处:网络
Given a string like: Su开发者_开发问答n Feb 06 2011 12:49:55 GMT-0800 (PST) How can you convert that to:

Given a string like:

Su开发者_开发问答n 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?


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


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


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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号