Reputation: 11686
I need to get the value of 00:00:00 AM GMT
(12am) for the current day and then convert it to unix time. How would/should I go about doing that in javascript? Is there an outside data source that is more reliable then server time? I will be doing this in node on the server.
Thanks!
EDIT: This is what I did. Do you see any problems with this? Thanks again!
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
Upvotes: 0
Views: 223
Reputation: 3700
Your method is right, but you have got a nasty bug in there, you are mixing local year with UTC date and month, for a few hours around new year, depending on time zone, the local and the UTC year is different, so if you use the wrong year your result will be a whole year off.
There are two interpretations of your question. Either you want a result based on the local time, so the result at any given time will depend on the time zone. Or you want a result based on UTC time that is the same no matter time zone, but sometimes for some users the result will not be the local date.
Local time:
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getMonth(),date.getDate()) / 1000
UTC:
date = new Date()
start_date = Date.UTC(date.getUTCFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
Upvotes: 2
Reputation: 11686
This is what I ended up doing for anyone else looking at this question.
date = new Date()
start_date = Date.UTC(date.getFullYear(),date.getUTCMonth(),date.getUTCDate()) / 1000
Please let me know if you see any reason this wouldn't work.
Upvotes: -1
Reputation: 5480
These links have some good answers. I love epochconverter.com it's saved me many hours of frustration. The essence of the answer is to use the Javascript Date object to handle all the nastiness of converting dates around. This is generally what you should do in any languages. If you are doing date manipulation by hand you will get it wrong.
http://www.epochconverter.com/programming/#javascript
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date
Upvotes: 0
Reputation: 2773
This is a good place to start:
var now = new Date();
var then = new Date(now.getFullYear(), now.getMonth(), now.getDate());
var epoch = then.getTime();
Not sure what you want to do about DST, so you'll need to look at: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset
Edit: To allow for different timezones:
var off = now.getTimezoneOffset() * 60000; /* tz is in mins so multiply to ms */
var midnight = new Date(then.getTime() - off);
var epoch = midnight.getTime();
Upvotes: 0