How to get the current seconds in the current month?
I am trying to calculate the current second in the current month, but I'm having trouble creating a simple f开发者_StackOverflowunction that does it.
My best guess involves using getTime() - the current milliseconds since January 1 1970 - and then subtracting X, where X is the number of milliseconds up to the end of the previous month.
Can you help me think of a better way to do this?
Thank you very much for your help.
Cheers,
function() {
var now = new Date().getTime(),
monthStart = new Date();
monthStart.setDate(1);
monthStart.setHours(0);
monthStart.setMinutes(0);
monthStart.setSeconds(0);
monthStart.setMilliseconds(0);
return Math.floor((now - monthStart.getTime()) / 1000);
}
You can create a Date instance and then call methods to set everything back to 00:00:00 on the first day of the month. Then you'd subtract that from the "now" timestamp.
The methods you'd call are setDate(1)
to set the day-of-month back to the start of the month, and then setHours()
, setMinutes()
, setSeconds()
, and setMilliseconds()
, passing all those zero.
Timestamps (return values from getTime()
are in milliseconds, so you'll divide your difference by 1000 to get the seconds into the month.
You can create a new date set to the first day of the month, like so:
var start = Date.parse("2010-11-01");
Then you can create a date for today:
var today = Date.now();
Then you just subtract them:
var seconds_in_month = today - start;
精彩评论