How to convert string into date? - javascript

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

Related

How to add days to current date in angular

Using this:
var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));
I get a date and time like this 2018-12-30T14:15:08.226Z, but only i want is this 2018-12-30. How can I retrieve just the date?
**This is Fixed. Thank You everyone who helps!!!
You're experiencing a JS problem, it has nothing to do with Angular.
This will use Date methods to get all the data you want:
const date = new Date ();
let dateString = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
// 2018-12-26
You can take advantage of the fact that the ISO 8601 format (what you are getting by implicitely converting to string) is well-codified with a separator T between the date and time in order to split it.
toISOString() gives you what you're seeing. split("T") splits the string into an array of strings with T as separator. [0] then extracts the first element.
var myDate = new Date(new Date().getTime()+(5*24*60*60*1000));
console.log(myDate.toISOString().split("T")[0]);

momentJS's toDate() returns invalid Date

I am getting in following format from PHP:
"end_date":{"date":"2017-02-17 18:52:31.000000","timezone_type":3,"timezone":"UTC"}}]
at JS/AngularJS end I am doing following:
var end_date = Lease.period_ferme[idx].end_date
$scope.frame[idx].end_date = moment(end_date).toDate()
console.log('After');
console.log($scope.frame[idx].end_date); //invalid date
if you pass an Object to the Moment constructor, that object should have fields named year, month, etc. Your object does not, so Moment can't parse it and decides it's invalid.
As mentioned in the comment attached to your question, try creating a Moment object with just the date string:
$scope.frame[idx].end_date = moment(end_date.date).toDate();
or, since your JSON specifies UTC, try creating a Moment object using Moment.utc:
$scope.frame[idx].end_date = moment.utc(end_date.date).toDate();

Convert integer to Date in node.js

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.

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"));

JavaScript: Convert "10/30/2015 2:43pm" to a Date object

As the title suggests, I need to know how to turn strings in the format of "10/30/2015 2:43pm" into JavaScript Date objects. The string comes from Datepair (http://jonthornton.github.io/Datepair.js/) and I need to insert it into Mongo DB as a date. I've got Moment.js too if that's useful in this situation.
Thanks!
Just try with:
new Date("10/30/2015 2:43pm".replace(/([ap]m)$/, " $1"))
Using moment, just provide the format as second parameter:
moment("10/30/2015 2:43pm", "MM/DD/YYYY hh:mma");

Categories