Invalid Date for some UTC Strings Javascript [duplicate] - javascript

This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
Trying to get UTC day of the week for any given timestamp on any given machine (w/ their own local time) I used:
var date = new Date(timestamp).toLocaleString('en-GB', { timeZone: 'UTC' });
Once I try to convert the date string to UTC date I get Invalid Date for some dates... it all seems pretty weird.
$ node
> date = new Date('15/08/2019, 00:00:00');
Invalid Date
> date = new Date('12/08/2019, 00:00:00');
2019-12-08T00:00:00.000Z
> date = new Date('15/08/2019');
Any idea where the Invalid Date issue may come from?

By converting the timestamps to strings using the "en-GB" locale, it looks like you're getting them in DD/MM/YYYY format. But in your second example, the strings are being interpreted as "MM/DD/YYYY" in whatever your default locale is, so the first call fails because 15 isn't a valid month number.

Related

Convert Numeric String to Readable Date Format in JavaScript [duplicate]

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
How do I format a date in JavaScript?
(68 answers)
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 1 year ago.
Let's say I have a string 2021-08-13 and want to convert this to August 13, 2021. How would you achieve this as it's not a date object.
In my mind I can think of setting each numeric month to a text version of that month and re-arrange, however seeing if there are better ways of doing this.
Simple: convert the string into a Date object and use the toLocaleString function.
If you want to get rid of the timezone so the date stays the same wherever the user is you can first convert it into an ISO string, get rid of the 'Z' in the end, and then convert it back into the Date object.
const dateString = '2021-08-13'
const localeOptions = {dateStyle: 'long'}
const dateTimezone = new Date(dateString).toLocaleString('en-US', localeOptions)
const dateWithoutTimezone = new Date(new Date(dateString).toISOString().slice(0,-1)).toLocaleString('en-US', localeOptions)
console.log(dateTimezone)
console.log(dateWithoutTimezone)
Convert your string date to a JS Date Object
let strDate = "2021-08-13";
let date = new Date(strDate);
console.log(date.toDateString())
Learn more about Date object here: JavaScript Date

Need to find the difference between two date in seconds [duplicate]

This question already has answers here:
Deprecation warning in Moment.js - Not in a recognized ISO format
(18 answers)
Closed 1 year ago.
I need to find difference between 2 dates in seconds , i am passing one date from front end and another date is current date but i am getting error
here is my code in front end
var a =moment().format('MM/DD/YYYY HH:mm:ss')
here is nodeJs code that I need to compare
var sesdate=moment(request.body.a).format("DD/MM/YYYY HH:mm:ss")
var startDate = moment(sesdate, "DD/MM/YYYY HH:mm:ss");
var currenDate = moment(new Date()).format("DD/MM/YYYY HH:mm:ss");
var endDate = moment(currenDate, "DD/MM/YYYY HH:mm:ss");
var result = 'Diff: ' + endDate.diff(startDate, 'seconds');
but i am getting expected output but getting warning message as
Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
If you already have two JavaScript DateTime objects, you can use the .getTime() method to get the milliseconds since 1970. Subtract one from the other and divide by 1000 to convert to seconds. You may need to take the absolute value if it's not guaranteed that one of them is always after the other.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
Alternatively, if you want to stick to your moment code, you'll need to convert your time format to one that is RFC2822 / ISO compatible. The top answer to this question will show you how to do that:
How do I format a date as ISO 8601 in moment.js?

how to get date of my localtime like 2020-03-11T02:59 with javascript [duplicate]

This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript? [duplicate]
(4 answers)
Closed 2 years ago.
i want to get my country date like this 2020-03-11T02:59 i try to JSON and toISOString but it give me the hours does not true
You can change the timezone with the offset at the end of the date string (e.g. -05:00).
And then create the date string you want using get functions.
You will need to pad the month, day, hour and minutes. However, the .get (eg .getMonth) functions return numbers, so you will also have to convert them to strings.
For example: event.getMonth().toString().padStart(2,0);
event is your date object.
.getMonth() returns the numeric value of the month of your date object
.toString() converts that number to a string value
.padStart(2,0) will add zeros to the front of the string if it is less than 2 characters.
// Set the date with timezone offset
let event = new Date("2020-03-11T02:59:00-08:00");
// Format your string
let newEvent = `${event.getFullYear()}-${event.getMonth().toString().padStart(2,0)}-${event.getDate().toString().padStart(2,0)}T${event.getHours().toString().padStart(2,0)}:${event.getMinutes().toString().padStart(2,0)}`;
console.log(newEvent);

Format date from DD.MM.YY format to DD/MM/YYYY format [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
How can I format date from DD.MM.YY format to any other format (preferably DD/MM/YYYY) with full 4 digits year value that I can input to new Date() by using javascript?
I find similar issue but in PHP code, is there an library that can convert that in javascript?
I'm getting Invalid Date error when inputting that date format to new Date()
Vanilla JavaScript can be used to convert the date string into a Date object by calling split(",") on the string, parseInt() on each returned array item, and then adding 1900 or 2000 to the year component based on your own needs. Date() takes the year, month, and day as arguments.
Once you have a JavaScript date object, a method like this using padStart() can output the date into the DD/MM/YYYY format.
See this example codepen: https://codepen.io/volleio/pen/BXWKyp

Moment js: Keep UTC date/time in UTC only [duplicate]

This question already has answers here:
moment js is returning wrong formatted values for an iso timestamp
(2 answers)
Closed 3 years ago.
date = moment(startDate).startOf('day');
date.format('2019-01-01't)
Above code is converting UTC date to local date. How do i keep UTC date UTC?
startDate is a datetime string in iso format
From the moment docs:
By default, moment parses and displays in local time.
If you want to parse or display a moment in UTC, you can use
moment.utc() instead of moment().
So even though your datestring is UTC and moment is correctly parsing the date, it still displays the output in local time unless you use moment.utc(). To display in utc:
const s = '2019-03-08T14:59:40Z';
const date = moment.utc(s).startOf('day').format();
console.log(date);
// 2019-03-08T00:00:00Z
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Categories

Resources