Get today's day from Date.now() - javascript

After getting the value from Date.now() I have tried extracting the date like that:
Date.now().getDate()
However, the getDate() function doesn't work on it. My whole application is based on dates that are retrieved from Date.now() and I need to get current day of the month from the Date.now() value. I have done some research and I can not find a solution to it.

Date.now() doesn't returns a Date instance:
The Date.now() method returns the number of milliseconds elapsed since
January 1, 1970 00:00:00 UTC
Being a number, it doesn't have .getDate() method. But, you can make use of Date without arguments to get a Date instance which has a .getDate() method:
If no arguments are provided, the constructor creates a JavaScript
Date object for the current date and time according to system
settings.
So this should work:
new Date().getDate(); // 3

Related

Convert Javascript current date time to UTC date time in milliseconds

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.

Create a Date Object with the year only

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()

I have hard to see when I would use date.parse and date.utc

The Date object provides method Date.parse and Date.UTC that can be called without creating a new Date object. Date.parse receives as its argument a string representing a date and time and return the number of milliseconds between midnight, January 1,1970 and the specified date and time.
Date method UTC return the number of milliseconds between midnight, January 1,1970 and the date and time specified as its argument.
So my question is when do anyone need to use cheese. I have hard to the usefulness
//Tony
First difference between them is their arguments list.
Date.UTC()
Date.UTC(year, month, day, hours, minutes, seconds, millisec);
Date.parse()
Date.parse(datestring);
Then, the other difference is that parse() uses local time.
Date.parse assumes local time if not specified. It gets the date in your machine local time
Date.UTC however gets the UTC time and takes additional parameters that you can use to pass hours, minutes, seconds, and milliseconds. UTC takes comma-delimited date parameters and returns the number of milliseconds between January 1, 1970, 00:00:00, universal time and the time you specified.

How do you check whether a date is UTC in Javascript?

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;

How to get current date and time in websql?

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

Categories

Resources