I wanted to know how to get current date and time and what datatype should i use to store it in websql, sorry for being such a noob...
You could create a Date object and store the numeric value of the date as the number of milliseconds since January 1, 1970, 00:00:00 UTC (negative for prior times).
var today = new Date();
today.getTime(); // returns "1337217238392"
Storing the milliseconds will allow you to read and parse however you like later. Its worth mentioning to check out date.js and moment.js
Related
I can't see a way to convert the current date/time in Javascript to a full date time in UTC. I need an equivalent to
var now = new Date().getTime();
but one that returns the UTC time in milliseconds
some thing like this
var UTCnow = new Date().getUTCTime();
I can't seem to see what I can use to make this happen in the JS Date object.
Any help would be appreciated.
Per the documentation:
The getTime() method returns the numeric value corresponding to the time for the specified date according to universal time.
getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone.
In other words, it already does what you are asking.
You can also do the same thing without instantiating a Date object:
var utcnow = Date.now();
Which the docs describe as:
The Date.now() method returns the number of milliseconds elapsed since January 1, 1970 00:00:00 UTC.
I'm used to create Date objects by using the fourth syntax from MDN as new Date(year, month, day, hours, minutes, seconds, milliseconds); But lately I tried to set a Date object with only a year (as new Date(2017)) but as you could expect it was treated as a value and considered the year as a number of milliseconds.
Is there any way of still easily use the year as is without changing the syntax and expect a correctly set Date ?
Two solutions come to my mind:
(1) Set the year argument to 2017 and set the month argument to 0 when constructing the date:
let d = new Date(2017, 0);
console.log(d.toString());
The arguments will be treated as local time; month and day of month will be January 1; all time components will be set to 0.
(2) Specify "2017T00:00" as the first and only argument when constructing the date:
let d = new Date("2017T00:00");
console.log(d.toString());
According to current specs this is a valid format and browsers are supposed to treat it as local time. The behavior is same as that of previous example.
If you are passing a single parameter (number or string), then it is taken as per doc
value
Integer value representing the number of milliseconds since January 1,
1970 00:00:00 UTC, with leap seconds ignored (Unix Epoch; but consider
that most Unix time stamp functions count in seconds).
dateString
String value representing a date. The string should be in a format
recognized by the Date.parse() method (IETF-compliant RFC 2822
timestamps and also a version of ISO8601).
Also as per doc
If at least two arguments are supplied, missing arguments are either
set to 1 (if day is missing) or 0 for all others.
You can pass one more parameter as 0 or null (or the actual value you want to set)
new Date(2017,0);
Demo
var date = new Date(2017,0);
console.log( date );
You could pass null as second argument:
new Date(2017, null);
However, without knowing the details of how missing values are interpreted, what do you think happens now? Will the date be initialized with the current month, day, hour, etc? Or something different?
Better be explicit and pass all arguments, so that you know what the code is doing half a year later.
I have another suggestion. You can just create a regular date object and set it's year. So at least you know to expect what the rest of the Date object values are.
var year = "2014";
var date = new Date();
date.setFullYear(year);
// console.log(year) => Wed Dec 27 2014 16:25:28 GMT+0200
Further reading - Date.prototype.setFullYear()
How to get timezone value for new Date(2017,05,31).toISOString()? It always comes as 000Z for any Date when the date is passed to the Date constructor. But for new Date().toISOString(), it gives the the timezone value.
new Date(2017,05,31).toISOString() gives "2017-05-30T18:30:00.000Z"
and new Date().toISOString() gives "2017-06-07T15:29:23.692Z". How to get timezone in UTC format for the past dates?
If you want the time to default to midnight in UTC, you can use Date.UTC(year, month, ...) to first create a timestamp based in UTC.
var utcMay31 = Date.UTC(2017, 4, 31); // note: 4 = May (0 = January)
Then, create the Date from that timestamp.
new Date(utcMay31).toUTCString(); // "Wed, 31 May 2017 00:00:00 GMT"
However, if you're wanting to know the timezone stored in the Date object, it doesn't actually have that. Dates represent an "instant" in time as the total number of milliseconds that have passed since Jan 1, 1970 00:00:00.000 UTC.
new Date().getTime(); // 1496851...
A Date can tell you the user's local offset from UTC in minutes at that instant.
new Date().getTimezoneOffset(); // e.g. 0, -480, 300
Otherwise, the timezone is limited to two choices when creating date strings, and the choice is based on the method used – user's local timezone or UTC.
new Date().toString(); // "now" in user's local time
new Date().toUTCString(); // "now" in UTC time
new Date().toISOString(); // "now" also in UTC time, alternate format
// etc.
You're confused ISO date values do not show the "time zone" instead they show the UTC time. Z stand for Zulu (UTC time).
2017-06-07T15:29:23.692Z
The bold part is not the time zone. It is the milli-seconds, the full time is in UTC. The reason it shows a 000Z in the set Date is because you didnt' set the milli-seconds.
If you want to display the time zone use toUTCString(). However it will display GMT which is UTC/Greenwich Time. To display the local time zone in a the date format you can use date.toLocaleString('en-US',{timeZoneName:'short'}) for example will display the date plus the local US time zone. Or you can use toString() which will display the GMT offset + the long local time zone.
In javascript, parsing, rendering and constructing dates will always assume local. It will convert to a timestamp, the number of milliseconds since 1-1-1970 00:00:00. JSON.stringify will convert to a UTC string, but legacy framworks use local dates. Always beware of this.
var myDate = new Date(); // this is now.
you can get your timezoneoffset (in minutes) with myDate.getTimezoneOffset(), but this will return the same offset for every date (aside from daylight saving time)
You shouldn't do this:
var utcDate = new Date(+d+60000*d.getTimezoneOffset());
// +d convert the date to a timespan.
// getTimezoneOffset() is in minutes
// *60000 makes that in milliseconds, the scale timespans operate upon
Date has a few methods to format dates, but always as local or UTC date. You need to do it manually if you want different time zones.
Note: the Date.UTC(...) function returns a timestamp. You sometimes see shifted dates, so they behave like UTC. But this causes problems later on.
var date = new Date(2000,1,1,12,0,0);
// DO NOT USE (breaks at start of daylight saving time)
// these are date/times that have the UTC-value,
// but Javascript treats them like local dates with this value.
utcDate1 = (+date-60000*d.getTimeZoneOffset()); // minus!!
utcDate2 = new Date(Date.UTC(2000,1,1,12,0,0));
// DO NOT USE (breaks at start of daylight saving time)
BTW
Edge, Chrome and Firefox display dates differently in the console: Edge and Firefox always shows local date, Chrome shows UTC. Also, if you change your timezone, Edge will screw up.
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
I've read this question:
How do you convert a JavaScript date to UTC?
and based on this I implemented this conversion in a dateTools module as follows:
[Update]
var dt, utcTime;
dt = new Date();
utcTime = new Date(Date.UTC(dt.getFullYear(),
dt.getMonth(),
dt.getDate(),
dt.getHours(),
dt.getMinutes(),
dt.getSeconds(),
dt.getMilliseconds()));
Now I'd like to write unit tests. My idea was to check whether the result is actually in UTC, but I don't know how.
All the toString, toUTCString and similar methods seem to be identical for the input (non UTC) and output (UTC) date.
Only the result of the getTime method differs.
Is there a way to check wheter a date is UTC in javascript? If not, is there a better idea to unit test this?
To give more context:
Only converting the it to a UTC string is not that helpful, because in the next step the date is sent to an Asp.net service and therefore converted to a string like:
'/Date([time])/'
with this code
var aspDate = '/Date(' + date.getTime() + ')/';
var aspDate = '/Date(' + date.getTime() + ')/';
This outputs the internal UNIX epoch value (UTC), which represents a timestamp. You can use the various toString methods to get a more verbose string representation of that timestamp:
.toString() uses the users timezone, result is something like "Fri Jan 25 2013 15:20:14 GMT+0100" (for me, at least, you might live in a different timezone)
.toUTCString() uses UTC, and the result will look like "Fri, 25 Jan 2013 14:20:15 GMT"
.toISOString() uses UTC, and formats the datestring according to ISO: "2013-01-25T14:20:20.061Z"
So how do we construct the time value that we want?
new Date() or Date.now() result in the current datetime. No matter what the user's timezone is, the timestamp is just the current moment.
new Date(year, month, …) uses the users timezone for constructing a timestamp from the single values. If you expect this to be the same across your user community, you are screwed. Even when not using time values but only dates it can lead to odd off-by-one errors.
You can use the setYear, setMonth, … and getYear, getMonth … methods to set/get single values on existing dates according to the users timezone. This is appropriate for input from/output to the user.
getTimezoneOffset() allows you to query the timezone that will be used for all these
new Date(timestring) and Date.parse cannot be trusted. If you feed them a string without explicit timezone denotation, the UA can act random. And if you want to feed a string with a proper format, you will be able to find a browser that does not accept it (old IEs, especially).
Date.UTC(year, month, …) allows you to construct a timestamp from values in the UTC timezone. This comes in handy for input/output of UTC strings.
Every get/set method has a UTC equivalent which you can also use for these things.
You can see now that your approach to get the user-timezone values and use them as if they were in UTC must be flawed. It means either dt or utcTime has the wrong value, although using the wrong output method may let it appear correct.
getTimezoneOffset
Syntax: object.getTimezoneOffset( ) This method
returns the difference in minutes between local time and Greenwich
Mean Time. This value is not a constant, as you might think, because
of the practice of using Daylight Saving Time.
i.e.
var myDate = new Date;
var myUTCDate = new Date(myDate - myDate.getTimezoneOffset() * 60000);
alert(myUTCDate);
note: 60000 is the number of milliseconds in a minute;