Convert integer to Date in node.js - javascript

I'm trying to convert a integer to a Date using node .js, and Date.
I know that this is a very common question but all the solutions that have been posted before have failed to help me.
I am getting the dates from a json file found at http://api.guardian.gg/chart/elo/4611686018432537994,
Example date: 1461110400000
What I've tried:
var date = String(new Date(elodata.x));
and
var date = String(new Date(parseInt(elodata.x)));
But I get invalid date as a result.
I realise that this might not be doable because I don't know how guardian.gg handles this data. But you never know.

You can pass in your value directly to a Date constructor in Javascript if it is an integer (which it appears to be in :
var date = new Date(elodata.x);
Likewise, you can also use the the setTime() function in Javascript to pass your integer value in if you already have an existing object :
var date = new Date();
d.setTime(elodata.x);
Example
var d1 = new Date(1461110400000);
console.log(`Constructor: ${d1}`);
var d2 = new Date();
d2.setTime(1461110400000);
console.log(`setTime(): ${d2}`);

When a single argument is passed to the Date constructor, if it's a string it will be parsed. The result of that is implementation dependent but if 1461110400000 is a string it will almost certainly give an invalid date.
If given a number, it's treated as a time value. So if you're passing a number, make sure it's type number:
var timeValue = '1461110400000';
console.log( new Date(+timeValue));
You could also use Number(timeValue) or parseInt(timeValue) but unary + is less to type.

Related

How to convert string into date?

in my application I want to show the last login of the user. From my backend I get this string: "lastLogin":"2022-02-22T06:02:53.585764600Z". In my frontend, I display it with:
<label class="lastVisitLabel">Last visit {{$store.state.user.lastLogin}}</label>
How can I format this string to a date type so I can use methods like .getHours() usw...
// Just pass string to new Date method
const customDate = new Date("2022-02-22T06:02:53.585764600Z");
// Test
console.log(customDate.getHours());
I already found the answer for my problem,
{{Date($store.state.user.lastLogin)}}
Just use this to cast the string inside the brackets
A possible solution is that you can pass the string date from the backend into a Date object. And only then you will be able to use Date methods.
or in your case
{{Date{$store.state.user.lastLogin}}
Please refer to the attached code as a reference.
//Value from DB
const strDate = "2022-02-22T06:02:53.585764600Z";
//Parse the date
const parsedDate = new Date(strDate);
document.querySelector("#display-date").textContent = parsedDate.getHours();
<h1 id="display-date"></h1>
MDN Date docs: Date
W3schools Date Objects

Formating date from milliseconds to this format: DD/MM/YYYY hh:mm:ss (US time locale) using native JS

I need to format this value in milliseconds "1543325996" to date like this "18/01/1970, 11:42:05 PM". I've already got the right result using 'toLocaleTimeString' function, but this result has String type. I need exactly Date type.
function dateFormat(date) {
var formDate = new Date(+date).toLocaleDateString("en-GB");
var formTime = new Date(+date).toLocaleTimeString("en-US");
var concatDate = (formDate + ", " + formTime);
// here I've got error 'Invalid Date'. I know that it's a wrong way, but don't know what to do.
var newDate = new Date(concatDate);
return newDate;
}
but this returns error "Invalid Date". Is there another way to convert String to Date?
...but this result has String type. I need exactly Date type.
Date objects don't have a format. Formatting is intrinsically a textual thing (e.g., string).
If you want Dates, then new Date(+date) is giving you that. There's nothing further required. Later, at some point, if you want to display that date in a textual form, use toLocaleDateString or Intl.DateTimeFormat or similar to format them in the way you want them formatted. But not until/unless you need to convert them to text (a string).

How to get date object from moment.js after formatting it

Using typescript, I am formatting my date with moment.js like this.
function getCreatedDate(objContainingDate: any): Date {
// Following line does not work since it is returning string,
// I need formatted date object to return
return moment(objContainingDate.createdDate).format("L")
}
The format method returns a string, how to convert it back to date object ?
This might be a delayed response.But, I think it can help others who still needs an answer.
https://momentjs.com/guides/#/lib-concepts/internal-properties/
To retrieve a native Date object from Moment, use .toDate()
You can directly get the Date object from Moment.
Using the date object with moment clones it and the original object is left intact to continue to use. But to convert it back just pass the formatted moment string into a new date object.
var myDateObj = new Date(2011, 9, 16);
var now = moment(myDateObj);
#Now convert it back to date object
var newDateObj = new Date(now.format("YYYY-MM-DDTHH:mm:ssZ"));

Convert INT to TIME using JS

I have converted a feed's published date "pubDate" to integer using JS.
Here is the code I used for it.
function timetoint(date){
var date = new Date(date);
return Math.round(date.getTime()/1000);
}
Now I need to convert the result of the above function back to a time format.
How can I do it?
Use the Date constructor :
var date = new Date(time*1000);

What does this javascript variable mean?

When I create variables I don't use brackets after equal sign.
Why does this code use brackets after equal sign? Can anyone explain this? I want to know what does it mean after equal sign.
var start = (new Date).valueOf(),
The paranthesis around new Date cause that to be evaluated first, so the date is created, and THEN call valueOf on the newly created date.
It's basically like doing
var d = new Date();
var start = d.valueOf();
but on one line.
However, it should be (new Date()).valueOf(). What is there right now will error out.
the intention of this is to shorten the following code:
var date = new Date();
var start = date.valueOf();
but you can't write:
var start = new Date().valueOf();
because theres no Date().valueOf() that can be used as constructor, so you'll have to add braces. the part in braces will be executed first (creating a new date), and valueOf() will be called on the result of the code in braces (read: on the constructed date). That said, the solution is what we got in your question:
var start = (new Date).valueOf();
the result of all this is a timestamp in milliseconds.
This method returns the equivalence of the Date object in milliseconds.
The milliseconds are expressed as an integer representing the number of milliseconds between midnight January 1, 1970 (GMT) to the date and time specified in the Date object.
Easy thing. new Date returns a date. Without brackets, it would be new Date.valueOf(). Since Date doesn't have a method valueOf(), this results in an error.
BUT, an instance of Date has this function. So we use brackets. (new Date).valueOf() is the same as
var start = new Date;
start.valueOf();
The wrapping parens around new Date evaluates the call to create a Date object then calls a method of the date object -> valueOf. An easier to understand example would be
(3 + 2) + 2; // = 7 - evaluates 5 then adds 2
the valueOf method is defined as:
Returns the primitive value of a Date object. Overrides the Object.prototype.valueOf method.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
You can actually achieve the same thing by
var start = +(new Date())
// returns the integer value of the date (in milliseconds)
// aka the primitive value

Categories