开发者

How do you get the unix timestamp for the start of today in javascript?

I realize that the current timestamp can be generated with the following...

var timestamp = Math.round((new Date()).getTime() / 1000);

What I'd like is the timestamp at the beginning of the current day. For example the current timestamp is roughly 1314297250, what I'd like to be able to generate is 1314230400 which is the beginning of today August 25th 2011.

Thanks开发者_C百科 for your help.


var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay / 1000;


Well, the cleanest and fastest way to do this is with:

long timestamp = 1314297250;
long beginOfDay = timestamp - (timestamp % 86400);

where 86400 is the number of seconds in one day


var now = new Date; // now

now.setHours(0);   // set hours to 0
now.setMinutes(0); // set minutes to 0
now.setSeconds(0); // set seconds to 0

var startOfDay = Math.floor(now / 1000); // divide by 1000, truncate milliseconds


var d = new Date();
d.setHours(0);
d.setMinutes(0);
d.setSeconds(0);
d.setMilliseconds(0);
var t = d / 1000;


Alternatively you could subtract the modulo of a days length in miliseconds e.g.

var day = 24*60*60*1000;
var start_of_today = Date.now() - Date.now() % day;


Luis Fontes' solution returns UTC time so it can be 1 hour (daylight saving time) different from setHours solution.

var d = new Date();
var t = d - (d % 86400000);

Simplified version of examples above (local time).

var d = new Date();
d.setHours(0,0,0,0);
var t = d / 1000;

Here you can find some performance tests: http://jsperf.com/calc-start-of-day


Another alternative for getting the beginning of the day is the following:

var now = new Date();
var beginningOfDay = new Date(now.getTime() -
                     now.getHours() * 60 * 60 * 1000 -
                     now.getMinutes() * 60 * 1000 -
                     now.getSeconds() * 1000 -
                     now.getMilliseconds());


var yoursystemday = new Date(new Date().getTime()-(120000*60+new Date().getTimezoneOffset()*60000));
yoursystemday = new Date();
var current_time_stamp = Math.round(yoursystemday.getTime()/1000);


For any date it's easy to get Timestamps of start/end of the date using ISO String of the date ('yyyy-mm-dd'):

var dateString = '2017-07-13';
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();

To get ISO String of today you would use (new Date()).toISOString().substring(0, 10) So to get TS for today:

var dateString = (new Date()).toISOString().substring(0, 10);
var startDateTS = new Date(`${dateString}T00:00:00.000Z`).valueOf();
var endDateTS = new Date(`${dateString}T23:59:59.999Z`).valueOf();


var now = new Date();
var startOfDay = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var timestamp = startOfDay.getTime() / 1000;
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜