I am wondering why those two Date objects have different output in console. In my opinion it should be the same but I can be wrong :)
var twoLinesSetup = new Date();
twoLinesSetup.setHours(0, 0, 0);
var inlineSetup = new Date().setHours(0, 0, 0)
console.log('twoLinesSetup', twoLinesSetup);
console.log('inlineSetup', inlineSetup);
And the console
twoLinesSetup: Mon May 08 2017 00:00:00 GMT+0200
inlineSetup :1494194400521
Why is it so?
twoLinesSetup contains the return value from instantiating the Date constructor, which returns a new Date instance object.
inlineSetup contains the return value from the setHours method, which returns the number of milliseconds since 1 January 1970 00:00:00 UTC
inlineSetup stores the return value of setHours. It is "A Number, representing the number of milliseconds between the date object and midnight January 1 1970"
twoLinesSetup is an actual object, which you do manipulate. The console output - the "toString" method if you want it like that, is the formatted string representation you see.
In theory you should see the same number by doing twoLinesSetup.getTime().
You're assigning the return value of the setHours() call to inlineSetup. This is not the Date object but a number representing the milliseconds of the date.
Related
I'd like to convert a timestamp into a date:
status_transitions:
{ finalized_at: 1557419382,
marked_uncollectible_at: null,
paid_at: 1557419384,
voided_at: null },
In particular, paid_at: 1557419384. But when I try new Date(1557419384) I do not get the expected result. If I use Date.setMilliseconds() I do.
What's especially strange is the output of Date.setMilliseconds()
const ms = 1557419384;
const fromConstructor = new Date(ms);
const fromFn = new Date();
const strangeOutput = fromFn.setMilliseconds(ms);
console.log(`Milliseconds: ${ms}`);
console.log(`Output from setMilliseconds: ${strangeOutput}`);
console.log(`Date from new Date(ms): ${fromConstructor}`);
console.log(`Date using setMilliseconds(ms): ${fromFn}`);
The output of the code above is:
Milliseconds: 1557419384
Output from setMilliseconds: 1558978824384
Date from new Date(ms): Sun Jan 18 1970 18:36:59 GMT-0600 (Central Standard Time)
Date using setMilliseconds(ms): Mon May 27 2019 12:40:24 GMT-0500 (Central Daylight Time)
Why does creating a new date from a number not yield the same result of setMilliseconds()? Also, why is the output from setMilliseconds() different than the actual milliseconds passed in?
I've read the docs and they seem to imply there should be no difference between these two methods.
Consider the example shown in the setMilliseconds() part of the docs here.
var theBigDay = new Date();
theBigDay.setMilliseconds(100);
Running this right now, this gives me the value 1557421875100. Notice only the last three digits are 100. Thus, it doesn't set the entire date object to 100, but only sets the milliseconds portion of the value. The rest is coming from new Date(), which is the current UTC-based timestamp.
As far as why you don't get the expected result from new Date(1557419384), that timestamp would appear to be in seconds rather than milliseconds. Multiply the value by 1000 and it gives a more reasonable value. (Unix timestamps are commonly expressed in whole seconds, which appears to be the case here.)
Why is the output from setMilliseconds() different than the actual milliseconds passed in?
Check the docs more closely. setMilliSeconds has a "Parameter:
A number between 0 and 999, representing the milliseconds." and its description states "If you specify a number outside the expected range, the date information in the Date object is updated accordingly. For example, if you specify 1005, the number of seconds is incremented by 1, and 5 is used for the milliseconds.".
So new Date() creates a date with the current time, and then you add your millisecond value to that.
Why does creating a new date from a number not yield the same result of setMilliseconds()?
I've read the docs and they seem to imply there should be no difference between these two methods.
What you were looking for is setTime. new Date().setTime(millseconds) creates an object that is equal to new Date(milliseconds).
When I try new Date(1557419384) I do not get the expected result.
As Matt Johnson noted, this value appears to be seconds not millisecond. Multiply it by 1000.
In a more general sense, I'm wondering if a value in Javascript can behave as if no variable were input, so that new Date(whatever) functions exactly like new Date().
null doesn't do this, instead creating a Date of (I think) -1 UNIX seconds (the very end of 1969). Is there a string that would work, e.g "now"?
You can use
new Date(Date.now());
to get the current date. Typing that into the console would return (for today's date)
Wed Jul 12 2017 14:03:16 GMT-0400 (Eastern Daylight Time)
To clarify, Date.now() returns the number of milliseconds since January 1, 1970 at 0:00 UTC.
You can read more about Date here : MDN: Date - JavaScript
No, there is no single value that would instruct new Date(…) with one argument to use the current time. However, you can call Date.now() or new Date() to get the current time, and then pass that to the constructor, which will return a new Date instance with that time.
Is there a way to indicate only the date portion of a Date() object, without indicating the time?
e.g.
var d = Date();
d.setFullYear(2015, 0, 13);
d.toString();
"Tue Jan 13 2015 00:00:00 GMT-0500 (EST)" // Wrong - I didn't set a time!
"Tue Jan 13 2015 NULL GMT-0500 (EST)" // Expected Result
I want to be able to tell the difference between a user who only inputed the Date portion, vs one who explicitly inputed both a Date and a Time
Not really. A Javascript Date object always has a time. You can leave it at midnight and ignore it if you want, but it'll still be there. It's up to you how you interpret it.
If you want to be able to represent a null time, you could interpret midnight to mean that, though then you would have no way to represent times that actually are midnight. If you want to be able to have a null time and still represent every possible time you would need to have two variables.
You could have:
// Date with null time
var date = new Date(2015, 0, 13); // time component ignored
var time = null;
// Date with non-null time
var date = new Date(2015, 0, 13); // time component ignored
var time = new Date(1970, 0, 1, 9, 30); // date component ignored
Note in the second example the year, month and day in the time component are arbitrary and won't be used, but they still need to be there if you want to create a Date object.
JavaScript Date objects are internally defined using number of milliseconds since January 1, 1970 UTC. Therefore you are stuck with the time part.
Try this code
var date = new Date(2015, 0, 13);
console.log(date.valueOf());
You'll get this output
1421125200000
Here is the standard definition...
ECMAScript Language Spec See page 165
From ECMA standard:
A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number
is called a time value. A time value may also be NaN, indicating that the Date object does not represent a
specific instant of time.
Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds
are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values
can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to
measure times to millisecond precision for any instant that is within approximately 285,616 years, either
forward or backward, from 01 January, 1970 UTC.
The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000
days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives
a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.
The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0
Dates are objects. As such, you can add properties to them as needed:
var date_only = new Date("2015-03-04");
date_only.time_is_meaningful = false;
var date_with_time = new Date("2015-03-04T10:47");
date_with_time.time_is_meaningful = true;
This is simpler and cleaner than your millisecond hack, and more
convenient than having two separate variables. You could then, if you
wish, subclass Date with a custom toString that checks the
time_is_meaningful property and acts accordingly.
You cannot remove the time information from a Date.
If you want to have both informations independently, use a Date for the date and ignore the time (e.g. ensure it's always exactly midnight for instance), and use another field to hold the time (it could be a Date where you ignore the date but not the time, or it could be one input text with formatted time, or several input texts with hour, minute, etc).
The UI representation is up to you.
I was trying to convert date object into long format (may be in milliseconds format) as we do in java.
So to fulfill my need, after some trial and error, I found below way which works for me:
var date = new Date();
var longFormat = date*1; // dont know what it does internally
console.log(longFormat); // output was 1380625095292
To verify, I reverse it using new Date(longFormat); and it gave me correct output. In short I was able to fulfill my need some how, but I am still blank what multiplication does internally ? When I tried to multiply current date with digit 2, it gave me some date of year 2057 !! does anyone know, what exactly happening ?
The long format displays the number of ticks after 01.01.1970, so for now its about 43 years.
* operator forces argument to be cast to number, I suppose, Date object has such casting probably with getTime().
You double the number of milliseconds - you get 43 more years, hence the 2057 (or so) year.
What you are getting when you multiply, is ticks
Visit: How to convert JavaScript date object into ticks
Also, when you * 2 it, you get the double value of ticks, so the date is of future
var date = new Date()
var ticks = date.getTime()
ref: Javascript Date Ticks
getTime returns the number of milliseconds since January 1, 1970. So when you * 1 it, you might have got value of this milliseconds. When you * 2 it, those milliseconds are doubled, and you get date of 2057!!
Dates are internally stored as a timestamp, which is a long-object (more info on timestamps). This is why you can create Dates with new Date(long). If you try to multiply a Date with an integer, this is what happens:
var date = new Date();
var longFormat = date*1;
// date*1 => date.getTime() * 1
console.log(longFormat); // output is 1380.....
Javascript tries to find the easiest conversion from date to a format that can be multiplied with the factor 1, which is in this case the internal long format
Just use a date object methods.
Read the docs: JavaScript Date object
var miliseconds=yourDateObject.getMiliseconds();
If You want to get ticks:
var ticks = ((yourDateObject.getTime() * 10000) + 621355968000000000);
or
var ticks = someDate.getTime();
Javascript date objects are based on a UTC time value that is milliseconds since 1 January 1970. It just so happens that Java uses the same epoch but the time value is seconds.
To get the time value, the getTime method can be used, or a mathematic operation can be applied to the date object, e.g.
var d = new Date();
alert(d.getTime()); // shows time value
alert(+d); // shows time value
The Date constructor also accepts a time value as an argument to create a date object, so to copy a date object you can do:
var d2 = new Date(+d);
If you do:
var d3 = new Date(2 * d);
you are effectively creating a date that is (very roughly):
1970 + (2013 - 1970) * 2 = 2056
You could try the parsing functionality of the Date constructor, whose result you then can stringify:
>
new Date("04/06/13").toString()
"Sun Apr 06 1913 00:00:00 GMT+0200"
// or something
But the parsing is implementation-dependent, and there won't be many engines that interpret your odd DD/MM/YY format correctly. If you had used MM/DD/YYYY, it probably would be recognized everywhere.
Instead, you want to ensure how it is parsed, so have to do it yourself and feed the single parts into the constructor:
var parts = "04/06/13".split("/"),
date = new Date(+parts[2]+2000, parts[1]-1, +parts[0]);
console.log(date.toString()); // Tue Jun 04 2013 00:00:00 GMT+0200
d.getTime().toString().search(/Wed/i)
I don't get it... typeof returns string, and if i copy and paste "Wed Jul 14 2010 15:35:53 GMT-0700 (PST)" and save it to the var str and do str.search(/Wed/i) it returns 0 but when i do it like above i always get -1, even tho, as i said, it returns a string typeof.
Any ideas how to check if Wed is in that str?
Just for reference, i'm looping through 7 days, checking for Wed, if it's wed, i save the current date and break out of the loop. If you know a better way let me know. Right now im just doing a while(x<=6)
getTime on a Date returns the number of milliseconds since 1 January 1970, so won't contain the string 'Wed'.
Perhaps you meant d.toString().search(/Wed/i) instead?
If d is an instance of Date, then a better way to check if it is a Wednesday would be to test if the result of getDay is 3:
d.getDay() == 3
The reason it returns -1 is that "Wed" will never appear in your string, because "getTime()" returns a big number: the number of milliseconds since the epoch.
Calling "toString()" on that big number still returns a big number, with the digits formatted as a string, as in "1278975122089". It does NOT return the date and time, as in "Mon Jul 12 15:49:59 PDT 2010".
The getTime() method returns the
number of milliseconds since midnight
of January 1, 1970 and the specified
date.
Try using the following instead, without the getTime() call:
d.toString().search(/Wed/i)