Converting Date with Javascript [duplicate] - javascript

This question already has answers here:
Convert .NET date format into JavaScript date
(1 answer)
Parsing a Auto-Generated .NET Date Object with Javascript/JQuery
(2 answers)
Closed 2 years ago.
I'm attempting to convert a Date that is returning from the database as /Date(1570474808430)/. I'd like to convert it as a standard date time result such as it's appearing in the database as : 2020-08-04 11:08:22.630. Is this something that is possible? I'm not entirely sure why it appears as date time in the database but is returning as /Date(1570474808430)/ on the front end.
I've attempted to approach this with the following code:
let oldDate = /Date(1570474808430)/
let updatedDate = new Date(oldDate);
console.log(updatedDate)
My expected result is to convert /Date(1570474808430)/ to a date time: 2020-08-04 11:08:22.630

Your snippet, perhaps unknown to you, actually tries to pass a regular expression literal to the Date constructor. What comes back from your API is actually a string - of the form /Date(xxx)/ where xxx appears to be a Unix timestamp. In order to translate this to a Javascript date object, we need to parse the timestamp out of that - assuming the data always has this format - and ironically, the simplest way to do that is probably a regular expression:
const oldDate = "/Date(1570474808430)/";
const timeStamp = Number(oldDate.match(/\/Date\((\d+)\)\//)[1]);
const updatedDate = new Date(timeStamp);
console.log(updatedDate)
This works if you can guarantee your data will be in this form - but frankly it is not good code, and will certainly lead to problems if your data isn't always in this format. The best thing you could do, if it's possible, would be to update your data so that it holds a sensible date-string in a standard format. Or failing that, at least a number representing the Unix timestamp, without the /Date(...)/ cruft.

Related

Turn a date represented as a string of milliseconds since UTC epoch to an actual date [duplicate]

This question already has answers here:
Converting milliseconds to a date (jQuery/JavaScript)
(12 answers)
Closed 1 year ago.
I have seen a variety of threads that are adjacent to this topic. However, my google fu has failed me so far.
I have a value on my server that is a date represented as a string. I am certain it is the milliseconds since the UTC epoch.
I will write it like this for stackOverflow:
const k = '1638400203941'
Date.parse(k); // NaN
const a = parseInt(k, 10);
Date.parse(a); // NaN
// ah ha! but what about...
Date.parse(Date.now() - a); // nope, NaN
I am sure this has been done a thousand times before but how do I do this?
To clarify, the goal is to parse my server's output, k = 1638400203941 into a date. YYYY-MM-DD or MM-DD-YYYY is ok.
edit: Somehow I didn't think to try the given solution. It was giving me Invalid date for some reason, guessing that I was passing in the string version instead of int. My mistake guys.
Just use new Date with you time in numerical format. I used + to convert the string to number.
const k = '1638400203941'
console.log(new Date(+k));

What date format is this? How do I convert it to a human readable date format in Javascript? [duplicate]

This question already has answers here:
Convert time interval given in seconds into more human readable form
(24 answers)
Closed 3 years ago.
I am returning some dates directly (unmodified) from the a database query to the front-end:
1540906457020
1540920856937
1540920856970
What is this dateformat called and how do I convert it to a human readable date, such as "03/21/2019" (or some variant with timestamp appended)?
It's based on the Unix timestamp, but it's counting milliseconds rather than seconds. (ES2015 calls this the "Time Value".) The Date object in Javascript uses this value underneath the surface. If you use the integer value as a parameter in the Date constructor, you'll get a Date object which should be handled quite well by most browsers.
const happyDateObject = new Date(1540920856937);
If you want a bit more control over what's going on, or want some more utilities that help you customize what the date looks like and how to manipulate it, I'd recommend the moment.js library. It's widely used because it's so useful. Since it's really just a wrapper for the standard Javascript Date object, moment objects convert quite easily to Date objects (when you need to do so). You'd construct the value in a similar way:
const happyMoment = moment(1540920856937)
This is a Unix timestamp (since Jan 01 1970), in milliseconds
You can convert it using e.g. this link here: https://www.epochconverter.com/
There are plenty of topics on how to convert timestamps to strings.
Start by using
new Date(1540920856937)

How to solve, in an elegant way and using JavaScript, the UTC problem, which subtracts a day when instantiating a Date in the format '2018-10-25'? [duplicate]

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I'm working on legacy system and in DB the birthday is coming this way '1992-05-18' in json. I am using AngularJS and when applying the data binding of this variable in an input type = "date", of an update form, it is necessary to instantiate a Date object. Like this:
//person.byrthday = '1992-04-26'
var person.birthday = new Date (person.birthday);
// after person.byrthday = '1992-04-25T00:00:00.000Z'
How can I solve this problem through Front End in an elegant way, without "breaking" two way data binding?
I find myself in Brasil UTC -03:00
There are a few ways to solve this problem. A quick and dirty solution could be to leverage moment.js. You can convert the response from the API to a true date format this way.
If you don't want to use an additionally library, you can make a function to parse the date string. You can do the following to parse is to become a correct date:
var dateSplit = person.birthday.split('-');
var mydate = new Date(dateSplit[0], dateSplit[1] - 1, dateSplit[2]);
person.birthday= mydate;
Take note that the month index starts at 0 (aka January=0). Hopefully this helps.

Getting the proper date from forms that are day/month/year

When writing a new date object with a string, one can write it as:
var someDay = new Date("12/01/2012");
This equals December 1st 2012.
However, what if the user has to fill in a date on a website where the format isn't month/day/year, but day/month/year? How would one go about creating a date object with the correct date then?
If you are getting the data as a string from another website, then you need to know the format in which that website provides you the date. There is no way around this because D-M-Y and M-D-Y are indistinguishable; even Y-M-D would be indistinguishable if they used a two-digit format for the year.
This hasn't been tested at all, but at worst the general idea should solve your problem.
var pattern = /^(\d+)\b(\d+)\b(\d+)$/;
if (!pattern.test(dateString))
return null;
var matches = dateString.match(pattern);
if (siteUsesDMY)
return new Date(matches[2], matches[1]-1, matches[0]);
if (siteUsesMDY)
return new Date(matches[2], matches[0]-1, matches[1]);
...
Pattern: This pattern supports any numeric representation of the date, assuming it has a breaking character between each unit. If you need to support a website that doesn't have a breaking character, you would need a different pattern that matched that website's exact format (i.e.: site sends DDMMYYYY, then pattern would be /^(\d{2})(\d{2})(\d{4})$/).
Also fixed the month parameter in date creation, as I just remembered that JavaScript uses 0-11 for months.

Is there a preexisting Javascript function to read "2009-09-16T11:10:00" as a date? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
How can I convert datetime microformat to local time in javascript?
Im writing up an ajax application where i have to interpret this date "2009-09-16T11:10:00" and output another string to something more readable.
That's the ISO 8601 date format. There's an example here. If that doesn't suit your needs then a quick google search should help.
No, there isn't a built-in function for doing that. You'd have to parse it yourself. Maybe something like this:
var s = "2009-09-16T11:10:00";
var tokens = s.split(/[\-T:]/);
var date = new Date(tokens[0], tokens[1] - 1, tokens[2],
tokens[3], tokens[4], tokens[5], 0);
Then access the date string with:
alert(date.toString());
Try this js library:
http://www.datejs.com
Pretty good and recognizes different date formats. You can also test your date right on the front page.

Categories

Resources