How to get the month out of a MySQL timestamp using JS
I have JSON outputting this timestamp 2011-05-03 12:00:开发者_运维技巧00. How would i use Javascript to just grab the month out of it?
If you have string "2011-05-03 12:00:00" then simply use
var month = "2011-05-03 12:00:00".split("-")[1];
or if you want to be able to extract all of the parts easily, use
var month = new Date("2011-05-03 12:00:00').getMonth();
If you want the number, just use .getMonth()
. It will return a number between 0 and 11, so you might want to add 1 (EDIT: this works in Chrome, BUT Firefox and IE9 does not seem to recognize the date format).
var month=new Date('2011-05-03 12:00:00').getMonth() + 1;
or if you just want the string representation with the leading zero:
var month=('2011-05-03 12:00:00').split('-')[1];
- jsFiddle Demo
- Javascript .split()
- Javascript Date Object
See my comment on your post above. If just the string
you can do a simple split:
var d = "2011-05-03 12:00:00"; var m = d.split('-')[1]
otherwise this seems to work:
new Date("2011-05-03 12:00:00").getMonth()+1
Don't split
the string. You're throwing most of the result away, so that's very wasteful.
Date
objects likewise (but worse).
Use this for great victory:
alert('2011-05-03 12:00:00'.substr(5,2));
// Result: '05'
How about looking at it in a different way:
What if your SQL's select statement also selects MONTH(timestamp)
and then store it in the JSON response as an additional field in the JSON object. Since it seems that getitng the month isn't universal between all browsers, this might be the most generic/easiest way to do it, less parsing, less error.
精彩评论