Milliseconds for current date in javascript - javascript

When I try the following
new Date().valueOf()
the result is 140082670954. For
new Date('05/23/2014').valueOf()
the result is 1400783400000.
There is a difference in the millisecond outputs. The second one is at 00:00:00 hrs but the first one is at 12pm with todays date.
I need to get the milliseconds as in the second one. How would I do this dynamically?

When you do:
new Date()
a new Date object is created with a time value for the current instant. When you do:
new Date('05/23/2014')
a new Date object is created at 00:00:00.000 on the specified date. If you want the equivalent using the constructor, then create the Date and set the time appropriately:
var d = new Date();
d.setHours(0,0,0,0);
NB
Please don't pass strings to the Date constructor. It calls Date.parse which is largely implementation dependent and inconsistent across browsers (even using the string format specified in ES5). Call the constructor with the required values:
new Date(2014, 4, 23);
noting that months are zero indexed so May is 4.

I take it that you want the milliseconds from midnight of a given day? I am afraid it won't be too simple, thanks to JavaScript's very constrained date-time API. You can extract the year, month, and day from the date object and create a new object from those:
var now = new Date();
var day = now.getDate();
var month = now.getMonth();
var year = now.getFullYear();
var today = new Date(year, month, day);
var millis = today.valueOf();
BTW: You mention that the first one "is at 12pm" - that depends on at what time you execute the statement. new Date() gives you the date including the current local time. So it appears that you tried it at roughly 12pm :-)

Related

JS setDate() not working as expected when Date is created with new Date('YYYY-MM-DD')

let a = new Date()
a.setDate(1) <--- this set date to the first date of this month.
However
let b = new Date ('2020-02-15')
b.setDate(1)
b.toISOString() -> returns'2020-02-02T00:00:00.000Z'
What's going on?
Timezones. The difference comes from the fact that you're initializing date a with the current time, and b at midnight local time, which (depending on the time of day where you are) can be a different day when represented in UTC. setDate() sets the "day" part of the Date object based on your locale.
let a = new Date()
a.setDate(1);
let b = new Date('2022-02-14');
b.setDate(1);
console.log("UTC:")
console.log(a.toISOString());
console.log(b.toISOString());
console.log('Local timezone:')
console.log(a.toLocaleString())
console.log(b.toLocaleString())
The above code will stop proving its point in about a month, so for the benefit of People Of The Futureā„¢ here is the current output:
UTC:
2022-02-01T17:11:37.114Z
2022-02-02T00:00:00.000Z
Local timezone:
2/1/2022, 12:11:37 PM
2/1/2022, 7:00:00 PM
I think it have something to do with your TimeZone and Time Settings
date.toISOString() always displays the date as
YYYY-MM-DDTHH:mm:ss.sssZ
Where Z means UTC+0 TimeZone
try adding the the time and the TimeZone when constructing the date
something like
let date = new Date('2020-02-12T00:00:00.000+02:00');

How to create a vanilla UTC time ticker?

I am working with a sun calculator and need a reference date/time that is NOT affected of timezones or DST changes. How much I am trying, javascript (and the browser, I presume), destroy the smooth run of the sun in the sky. How can I create a date/time that I can step through in minute, hour, day, month steps without this damn DST interfering it? - Zones and localizing is no problem.
The promblem seems to be, that all of my defined UTC dates always do jump into and out of the DST. Only the real sun doesn't.
Some of my unhappy tries here:
{ //UTC DATE OVERALL
myutcdate=new Date(mydate.getUTCFullYear(),mydate.getUTCMonth(),mydate.getUTCDate(),mydate.getUTCHours(),mydate.getUTCMinutes());
//myutcdate=new Date(mydate.valueOf()-localoffset*60*60*1000);
//var utcoffset=myutcdate.getTimezoneOffset/-60;
//if(mydate.isDST() && !myutcdate.isDST())myutcdate.setHours(myutcdate.getHours()+1);
//if(myutcdate.isDST())myutcdate.setHours(myutcdate.getHours()-1);
//myutcdate= new Date(mydate.getUTCFullYear(),mydate.getUTCMonth(),mydate.getUTCDate(),mydate.getUTCHours(),mydate.getUTCMinutes(),);
//myutcdate= new Date(mydate.toUTCString());
//myutcdate= new Date(mydate).toISOString();// returns just a sring, not a date, and cannot be converted to a date
//myutcdate= new Date(mydate.toISOString());//returns plain local time
//myutc= new Date(mydate.valueOf() - parseInt(localoffset)*60*60*1000 );
//myutcdate=Date.UTC(myutc.getFullYear(),myutc.getMonth(),myutc.getDate(),myutc.getHours(),myutc.getMinutes());
//myutcdate= new Date(myutcdate);
//document.getElementById('utcdate').innerHTML=myutcdate;//.toSimpleIso(); //myutcdate with own format
//document.getElementById('utcdate').innerHTML=myutcdate.getUTCFullYear()+"-"+String(myutcdate.getUTCMonth()+1)+"-"+myutcdate.getUTCDate()+" "+myutcdate.getUTCHours()+":"+myutcdate.getUTCMinutes();//.toSimpleIso(); //Yields to reducing double the zone of source date
//document.getElementById('utcdate').innerHTML=myutcdate.getFullYear()+"-"+String(myutcdate.getMonth()+1)+"-"+myutcdate.getDate()+" "+myutcdate.getHours()+":"+myutcdate.getMinutes();//.toSimpleIso(); //myutcdate with own format
document.getElementById('utcdate').innerHTML=mydate.toISOString();
}
The Date constructor assumes local, to get UTC, use Date.UTC to generate the time value, e.g.
// Instead of
new Date(mydate.getUTCFullYear(), ...)
// Use
new Date(Date.UTC(mydate.getUTCFullYear(),...))
//-------^^^^^^^^
Then use UTC methods for everything.
var d = new Date();
// Copy date using UTC values
var c = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()));
console.log(d.toISOString());
console.log(c.toISOString());

JS: Convert Today's Date to ISOString() with Fixed Time

I'm trying to convert today's date to an ISO standard string but with the fixed time of T00:00:00.000Z.
I can get as far as returning a ISO string of today's date and time:
var isoDate = new Date().toISOString();
// returns "2015-10-27T22:36:19.704Z"
But I wanted to know if it's possible to have a fixed time, so it should return:
"2015-10-27T00:00:00.000Z"
Is this possible?
Any help is appreciated. Thanks in advance!
To get the current UTC date at midnight:
var d = new Date();
d.setUTCHours(0);
d.setUTCMinutes(0);
d.setUTCSeconds(0);
d.setUTCMilliseconds(0);
var output = d.toISOString();
To get the current local date, with the time portion set to UTC midnight:
var d = new Date();
var ts = Date.UTC(d.getFullYear(), d.getMonth(), d.getDate());
var output = new Date(ts).toISOString();
As for which to use, think through your requirements very carefully, The current UTC date and the local date may indeed be two different days.
For example, when it's midnight (00:00) October 27th in UTC, it's 8:00 PM on October 26th in New York.
Also, consider using moment.js, which makes operations like either of these much easier with the startOf('day') and .utc() functions.

Create now/subtract dates/month with format of "2014-08-04T17:19:00-07:00" in JavaScript

How do I create the time now and format it to a string with format of "2014-08-04T17:19:00-07:00"? Using moment.js or any other JavaScript?
I will also need to create 2 new, one to subtract a week from now, one to subtract a month from now, but also with this format.
Simply enough:
var d = Date.now(); //For current time in MS
d = new Date(); //For current time wrapped in the object.
d.toISOString();
For more on ISO String read this or that.
If you want to do any Date arithmetic, like adding a month, just add/subtract the number of milliseconds for that unit to your date object.
Additionally, if you don't want time in Zulu, you can use String manipulation to drop the Z and add the proper zone. Don't forget to account for the difference in time zones!
You can do this:
var date = new Date();
date.toISOString();
> "2014-08-05T17:22:08.030Z"
// Subtract one week:
var before = date;
before.setDate(date.getDate()-7);
before.toISOString();
> "2014-07-29T17:22:08.030Z"

Javascript, Time and Date: Getting the next day, week, month, year, etc

Based on a given millisecond timestamp, what's the 'correct' way to get the next day, week, month, year, etc.? That is, without having to do some kind of binary search with raw millisecond timestamp values or something silly like that.
Edit: Does using the Date constructor with a month, day, hour, etc. value beyond the limit translate it to the next year, month, day, etc.?
function getNextDate()
{
var today = new Date();
var d = today.getDate();
var m = today.getMonth();
var y = today.getYear();
var NextDate= new Date(y, m, d+1);
var Ndate=NextDate.getMonth()+1+"/"+NextDate.getDate()+"/"+NextDate.getYear();
alert(Ndate);
}
If the millisecond timestamp that you have is (conveniently!) the number of milliseconds since 1970/01/01 then you can simply create a new Date object from the millisecond value new Date(milliseconds) and use it as outlined in Misnomer's answer.
If your timestamp is based from onther point in time then you can simply workout the offset (in milliseconds) from 1970/01/01 and subtract that from the timestamp before creating the Date object.
As always when dealing with dates, be clear if you are dealing in local or UTC times.
w3schools date object
w3schools full date reference

Categories