I am trying to convert milliseconds to a date using the javascript using:
new Date(Milliseconds);
constructor, but when I give it a milliseconds value of say 1372439683000 it returns invalid date. If I go to a site that converts milliseconds to date it returns the correct date.
Any ideas why?
You're not using a number, you're using a string that looks like a number. According to MDN, when you pass a string into Date, it expects
a format recognized by the parse method (IETF-compliant RFC 2822 timestamps).
An example of such a string is "December 17, 1995 03:24:00", but you're passing in a string that looks like "1372439683000", which is not able to be parsed.
Convert Milliseconds to a number using parseInt, or a unary +:
new Date(+Milliseconds);
new Date(parseInt(Milliseconds,10));
The Date function is case-sensitive:
new Date(Milliseconds);
instead of this
new date(Milliseconds);
use this
new Date(Milliseconds);
your statement will give you date is not defined error
Is important to note that the timestamp parameter MUST be a number, it cannot be a string.
new Date(1631793000000).toLocaleString('en-GB', { timeZone: 'America/Argentina/Buenos_Aires' });
// Returns: '16/09/2021, 08:50:00'
new Date("1631793000000").toLocaleString('en-GB', { timeZone: 'America/Argentina/Buenos_Aires' });
// Returns: 'Invalid Date'
In case you're receiving the timestamp as string, you can simply wrap it around parseInt(): parseInt(your_ts_string)
I was getting this error due to a different reason.
I read a key from redis whose value is a json.
client.get(someid, function(error, somevalue){});
Now i was trying to access the fields inside somevalue (which is a string), like somevalue.start_time, without parsing to JSON object.
This was returning "undefined" which if passed to Date constructor, new Date(somevalue.start_time) returns "Invalid date".
So first using JSON.parse(somevalue) to get JSON object before accessing fields inside the json solved the problem.
Related
I am using Robot Framework and need to remove the time from a date. I use Get Current Date (exclude milliseconds) and pass value to a variable. The goal is to strip the time from the date. I have a syntax error which I cannot resolve.
${date}= Get Current Date exclude_millis=true
Execute Javascript Date.toDateString(${date})
Error: JavascriptException: Message: javascript error: missing ) after argument list
The toDateString() method returns the date portion of a Date object as a human-readable string.
Syntax:
dateObj.toDateString();
Parameters:
This method does not take any parameters.
Return value:
A string representing the date portion of the given Date object.
Example:
var d = new Date();
console.log(d.toDateString());
Output:
"Wed Apr 12 2017"
I researched about converting date into string in ISO format, and I found two methods to do that giving me the same result '2022-07-29T06:46:54.085Z':
(new Date()).toISOString()
JSON.parse(JSON.stringify(new Date()))
Question:
Does JS make two approaches/algorithms of converting date or just one function code just call on different object JSON or Date, If So Which one is the best to use?
First of all: less code, easier to maintain
So, new Date().toISOString() is simplest way to return string in ISO format.
Regarding question:
No. The output is the same, because of JSON.stringify logic underneath that returns:
JSON.stringify(new Date())
'"2022-07-29T18:58:14.411Z"'
Because:
The instances of Date implement the toJSON() function by returning a string (the same as date.toISOString()). Thus, they are treated as strings.
Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
(new Date).toJSON()
'2022-07-29T18:58:14.411Z'
JSON.parse(JSON.stringify(new Date())) is just the same as new Date().toJSON(). And in the docs for that method we can see
Calling toJSON() returns a string (using toISOString()) representing the Date object's value.
So they're having exactly the same result, calling toISOString() directly is just much more straightforward.
If an object passed to JSON.stringify has a toJSON method, then it's used to set the value within the JSON text (see SerializeJSONProperty step 2.b).
Date instances have a toJSON method that is defined as returning the same value as Date.prototype.toISOString.
I.e.
date.toJSON() === date.toISOString()
by design.
In typescript, I am setting an object's date field in following way.
at: new Date("2017-06-24"+"T"+"22:00"+"Z")
Then I am sending that object as POST body to my webservice. In body, date field looks like "at":"2017-06-24T22:00:00.000Z"
But I want o get rid of milliseconds part. How can I do that ?
You can format the String you have from the form input values as
new Date("2017-06-24"+"T"+"22:00"+"Z").toISOString().split('.')[0]+"Z"
else you can directly generate the String from your form input values
`${this.form.value.Date}T${this.form.value.Time}Z`
in both the above cases you have the String output as 2017-06-24T22:00:00Z
and not the Date type.
Date constructor in Js will have the milliseconds field
so it will be an issue if at in your Object is defined as a Date instead of a String.
console.log(new Date('2016-05-24').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/26/2016').toISOString()); // '2016-05-23T23:00:00.000Z' // why?
I am sending data to the server to parse and want to ensure that server will encode my date correctly.
What is the simplest way to convert date to string as '2016-05-24T00:00:00.000Z' in both cases?
Thanks
console.log(new Date('2016-05-24 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
console.log(new Date('05/24/2016 GMT').toISOString()); // '2016-05-24T00:00:00.000Z'
Append the timezone to the date before creating a new date object so that the string parsing code in the Date constructor doesn't get confused. Always disambiguate if possible.
Your code was using different timezones for each parse because of the way the dates were formatted. One was using +0 timezone, other was using -1 timezone hence the date being pulled back an hour when the ISO string was created.
One is parsing in UTC time, one is parsing in local time.
new Date('2016-05-24').toISOString() // '2016-05-24T00:00:00.000Z'
new Date('05/24/2016').toISOString() // '2016-05-24T07:00:00.000Z'
Playing around, here's one solution:
new Date(new Date('05/24/2016') - (new Date()).getTimezoneOffset() * 60000).toISOString() // '2016-05-24T00:00:00.000Z'
The strategy:
Create the new offset date
Subtract the offset
Create a new date from that result
Reference links:
javascript toISOString() ignores timezone offset
Why does Date.parse give incorrect results?
On further consideration, I'd recommend parsing the date string into something that is "universal" before passing it to the date constructor. Something like:
var tmp = ('05/24/2016').split('//');
var universal = [tmp[2], tmp[0], tmp[1]].join('-'); // 2016-05-24
...
Also, Moment.js does this sort of thing very neatly.
Use the getDate(), getMonth() and getFullYear() methods to strip out what you need.
We store every date data in ISO format using new Date().toISOString().
I tried to convert this ISO formatted date into Date object in node.js but I get Invalid Date response.
date string is isoDate = 2014-07-09T14:00:00.000Z
and I did console.log on Date.parse(isoDate); and new Date(isoDate);
but each returns NaN and Invalid Date.
I checked if the date string contains any invisible wrong character but they are fine and can be converted on browser console.
does this mean I need to convert the string manually and create Date object with parsed string?
Thanks for reading.
Try using moment library. It has a lot of functionality to work with dates and can easily be used both on client and server side. Calling moment("2014-07-09T14:00:00.000Z").toDate() would convert your string to a Date JavaScript Object, using this library.
I am posting this answer just in case somebody experience this like I did.
What happened to me is I thought I was sending an ISOString from the browser
{
startDate: date.startDate
}
which in fact I was sending a moment instance as parameter
When I checked in the network inspector I found out that the data being sent is in ISO format - yes, but it is enclosed in double quote ""
{
startDate: "2016-12-31T16:00:00.000Z"
}
it should not be enclosed in double qoutes and should look like this
{
startDate: 2016-12-31T16:00:00.000Z
}
what worked for me is to parse the moment to iso string
{
startDate: date.startDate.toISOString()
}