Parse string that may contain invalid daylight date - javascript

I need help to convert input string that looks something like 20160313023000 (invalid daylight saving date) to date in yyyyMMddHHmmss format using JavasScript.
I tried new Date('20160313023000').getTime() but the output that I get is 1969/12/31 19:00:00.000

That will parse your date:
function parseDate(date) {
// format: yyyyMMddHHmmss
var parsedDate = new Date(date.substr(0, 4),
date.substr(4, 2),
date.substr(6, 2),
date.substr(8, 2),
date.substr(10, 2),
date.substr(12, 2));
console.log(parsedDate);
}
parseDate("20160313023000");
But the "invalid daylight saving" actually depends on your locale.

Related

Subtract x days from a String Date - React

Suppose I've got a date in string format, such as "2021-07-19". How can I subtract x days from this date that is represented as a string?
I have tried to convert the string into a date first, then subtract the number of days, and convert back to a string, but that doesn't work.
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = previousDayDate.toString()
The ultimate result should be "2021-07-18". Instead, I get the date as a full string: Sun Jul 18 2021 01:00:00 GMT+0100 (British Summer Time)
The reason you get the wrong date is that "2021-07-19" is parsed by built–in parsers as UTC, but all the other methods you're using are local, so you appear to get the wrong date or time. Other than that, your algorithm is sound. Just parse the string as local to being with:
// Parse string in YYYY-MM-DD format as local
function parseISOLocal(s) {
let [Y, M, D] = s.split(/\W/);
return new Date(Y, M-1, D);
}
console.log(parseISOLocal('2021-07-20').toString());
This is a very common issue.
Note, the snippet below didn't work in my locale until I changed the input date to YYYY-MM-DD.
// const dateString = "2021-19-07" - your format
const dateString = "2021-07-19" // format testable in my locale
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayDateString = `${previousDayDate.getFullYear()}-${('0' + (previousDayDate.getMonth()+1)).slice(-2)}-${('0' + previousDayDate.getDate()).slice(-2)}`;
console.log(previousDayDateString)
Using Moment.js
const dateString = moment("2021-07-19", "YYYY-MM-DD").startOf("day")
const previousDayDateString = dateString.subtract(1, "days").format("YYYY-MM-DD");
Thank you all for the suggestions. I followed the same convention as Spencer's comment above (How to format a JavaScript date?) by doing:
const dateString = "2021-07-19"
const previousDayDate = new Date(dateString)
previousDayDate.setDate(previousDayDate.getDate() - 1)
const previousDayString = previousDayDate.toLocaleDateString("en-CA").split(",")[0]
console.log(previousDayString)

Parsing datetime with Z and T in javascript

I'm currently using an API that's returning a timestamp in a weird format that I'm struggling to parse into a unix timestamp for my database, the result I'm receiving is:
"date": "20190412T131518.000Z",
I've tried using:
var date = new Date(array.date);
console.log(date.parse);
Which just returns NaN so I'm unsure where to go with it
You could add some dashes and colons.
20190412T131518.000Z // input
2019-04-12T13:15:18.000Z // needed format
It looks like, that Date does not fully accept date string in ISO 8601 format. It respects only a version from the standard in the form
YYYY-MM-DDTHH:mm:ss.sssZ
var string = "20190412T131518.000Z",
date = new Date(string.replace(/(....)(..)(.....)(..)(.*)/, '$1-$2-$3:$4:$5'));
console.log(date);
You can parse from the string to the Date object as below:
let rawDate = "20190412T131518.000Z";
let myDate = new Date(Date.UTC(
rawDate.substr(0, 4),
rawDate.substr(4, 2),
rawDate.substr(6, 2),
rawDate.substr(9, 2),
rawDate.substr(11, 2),
rawDate.substr(13, 2)
));
console.log(myDate);

Check if a date string is in ISO and UTC format

I have a string with this format 2018-02-26T23:10:00.780Z I would like to check if it's in ISO8601 and UTC format.
let date= '2011-10-05T14:48:00.000Z';
const error;
var dateParsed= Date.parse(date);
if(dateParsed.toISOString()==dateParsed && dateParsed.toUTCString()==dateParsed) {
return date;
}
else {
throw new BadRequestException('Validation failed');
}
The problems here are:
I don't catch to error message
Date.parse() change the format of string date to 1317826080000 so to could not compare it to ISO or UTC format.
I would avoid using libraries like moment.js
Try this - you need to actually create a date object rather than parsing the string
NOTE: This will test the string AS YOU POSTED IT.
YYYY-MM-DDTHH:MN:SS.MSSZ
It will fail on valid ISO8601 dates like
Date: 2018-10-18
Combined date and time in UTC: 2018-10-18T08:04:30+00:00 (without the Z and TZ in 00:00)
2018-10-18T08:04:30Z
20181018T080430Z
Week: 2018-W42
Date with week number: 2018-W42-4
Date without year: --10-18 (last in ISO8601:2000, in use by RFC 6350[2])
Ordinal date: 2018-291
It will no longer accept INVALID date strings
function isIsoDate(str) {
if (!/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}.\d{3}Z/.test(str)) return false;
const d = new Date(str);
return d instanceof Date && !isNaN(d) && d.toISOString()===str; // valid date
}
console.log(isIsoDate('2011-10-05T14:48:00.000Z'))
console.log(isIsoDate('2018-11-10T11:22:33+00:00'));
console.log(isIsoDate('2011-10-05T14:99:00.000Z')); // invalid time part
let date= '2011-10-05T14:48:00.000Z';
var dateParsed= new Date(Date.parse(date));
//dateParsed
//output: Wed Oct 05 2011 19:48:00 GMT+0500 (Pakistan Standard Time)
if(dateParsed.toISOString()==date) {
//Date is in ISO
}else if(dateParsed.toUTCString()==date){
//DATE os om UTC Format
}
I think what you want is:
let date= '2011-10-05T14:48:00.000Z';
const dateParsed = new Date(Date.parse(date))
if(dateParsed.toUTCString() === new Date(d).toUTCString()){
return date;
} else {
throw new BadRequestException('Validation failed');
}
I hope that is clear!

How to specify timestamp format when converting to human readable string in JS

I need to display a formatted date from a timestamp provided by Google Analytics
Standard solution like
var date = new Date(timestamp * 1000);
var formatted = date.toString();
produces wrong value Jan 01 1970. That's because of timestamp format.
In PHP I can specify the timestamp format:
\DateTime::createFromFormat('Ymd', $timestamp);
How to do this in JS?
Since the dates you are receiving are formatted as YYYYMMDD, not as a Unix
timestamp, you can parse it by
extracting the year, month and date using String.prototype.slice.
var timestamp = '20170306',
year = parseInt(timestamp.slice(0, 4), 10),
month = parseInt(timestamp.slice(5, 6), 10),
day = parseInt(timestamp.slice(7, 8), 10);
// - 1 because the Date constructor expects a 0-based month
date = new Date(Date.UTC(year, month - 1, day)),
gmt = date.toGMTString(),
local = date.toString();
console.log('GMT:', gmt); // Mon, 06 Mar 2017 00:00:00 GMT
console.log('Local:', local);
This assumes that the dates you are using are in UTC (which they likely are). Date.UTC creates a timestamp (in milliseconds since Unix epoch) and then feeds it into new Date() which uses it to create a Date object representing that time. .toGMTString() outputs the date formatted for the GMT timezone. To output it formatted in local time, use .toString() instead.
try this type:
var userDate = new Date();
var day = userDate.getDate();
var month = userDate.getMonth() + 1;
var year = userDate.getFullYear();
alert("Date Formate is :"+year+"-"+month + "-" + day);
In javascript you can use an external library like moment.js
var date = moment.unix(timestamp);
date.format("YYYY MM DD");
See detail about .format here https://momentjs.com/docs/#/displaying/format/

Regarding JavaScript new Date() and Date.parse()

var exampleDate='23-12-2010 23:12:00';
I want to convert above string into a date and have tried a couple things:
var date = new Date(exampleDate); //returns invalid Date
var date1 = Date.parse(exampleDate); //returns NAN
This code is running fine in IE and Opera, but date is returning me an invalid Date and date1 is returning NAN in Firefox. What should I do?
The string in your example is not in any of the standard formats recognized by browsers. The ECMAScript specification requires browsers to be able to parse only one standard format:
The format is as follows: YYYY-MM-DDTHH:mm:ss.sssZ
This format includes date-only forms:
YYYY
YYYY-MM
YYYY-MM-DD
It also includes time-only forms with an optional time zone offset appended:
THH:mm
THH:mm:ss
THH:mm:ss.sss
Also included are “date-times” which may be any combination of the above.
If the String does not conform to that format the function may fall back to any
implementation-specific heuristics or implementation-specific date formats. Unrecognizable Strings or dates
containing illegal element values in the format String shall cause Date.parse to return NaN.
So in your example, using 2010-12-23T23:12:00 is the only string guaranteed to work. In practice, most browsers also allow dates of the format DD Month YYYY or Month DD, YYYY, so strings like 23 Dec 2010 and Dec 23, 2010 could also work.
Above format is only supported in IE and Chrome.
so try with another formats. following are some formats and there supporting browsers.
<script type="text/javascript">
//var dateString = "03/20/2008"; // mm/dd/yyyy [IE, FF]
var dateString = "2008/03/20"; // yyyy/mm/dd [IE, FF]
// var dateString = "03-20-2008"; // mm-dd-yyyy [IE, Chrome]
// var dateString = "March 20, 2008"; // mmmm dd, yyyy [IE, FF]
// var dateString = "Mar 20, 2008"; // mmm dd, yyyy [IE, FF]
// Initalize the Date object by passing the date string variable
var myDate = new Date(dateString);
alert(myDate);
</script>
You could parse it manually with a regular expression then call the date constructor with the date elements, as such:
var parseDate = function(s) {
var re = /^(\d\d)-(\d\d)-(\d{4}) (\d\d):(\d\d):(\d\d)$/;
var m = re.exec(s);
return m ? new Date(m[3], m[2]-1, m[1], m[4], m[5], m[6]) : null;
};
var dateStr = '23-12-2010 23:12:00';
parseDate(dateStr).toString(); //=> Thu Dec 23 2010 23:12:00 GMT-0800
JavaScript should support conversion at least from the following dateStrings:
* yyyy/MM/dd
* MM/dd/yyyy
* MMMM dd, yyyy
* MMM dd, yyyy
Try with:
var exampleDate='12/23/2010 23:12:00';
var date = new Date(exampleDate);
Use datejs and this code:
var exampleDate='23-12-2010 23:12:00';
var myDate = Date.parseExact(exampleDate, 'dd-MM-yyyy hh:mm:ss');
myDate should be a correctly constructed Date object.
Just use in this format:
var exampleDate='2010-12-23 23:12:00';
#casablanca has a good answer but it's been 10+ years and this still has a lot of weight in Google so I thought I'd update with a new answer.
TL;DR
// Use an ISO or Unix time string to generate `Month DD, YYYY`
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${newDate.getDate()}, ${newDate.getFullYear()}`
// yields: December, 23 2010 (if you want date suffix, read until the end)
Background: Dates come in a lot of formats, but you're mostly going to receive:
An ISO 8601 format date (YYYY-MM-DDTHH:mm:ss.sssZ) where Z is a UTC timezone offset. You might also get a subset of this (ie, YYYY-MM-DD)
Unix timestamp format date (1539734400), where the number is literally the total amount of milliseconds since the beginning of Unix time, Jan 1st 1970.
Basics: JS has a built-in Date prototype that accepts ISO 8601 and derivatives (of just time or just date). You can instantiate with new Date and return a date object OR you can use the Date.parse() method to return a Unix timestamp.
const dateObj = new Date('23-12-2010:23:12:00') // returns date object
const dateDateOnly = new Date('23-12-2010') // returns date object
const dateTimeOnly = new Date('23:12:00') // returns date object
const dateString = Date.parse('23-12-2010:23:12:00') // returns Unix timestamp string
You can also break the date into 7 parameters: the year, the month (starting from 0), the day, the hour, the minutes, seconds and milliseconds with the time zone offset - NOTE, I've used the multi-params approach only once in my career. Since I'm in Texas I get, UTC-5 (Central Time) when I run the following:
const dateByParam = new Date(2021, 2, 26, 13, 50, 13, 30) // Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time)
New-ish Stuff toLocaleString: Typically, the return from the Date object is still pretty dense like our last example (Fri Mar 26 2021 13:50:13 GMT-0500 (Central Daylight Time) so additional methods have been added to help developers.
Typically with a date, I want something like March 21st, 2021 - the day and year have been easy to get for a long time:
// Assuming myDate is a JS Date object...
myDate.getDate() // date on the calendar, ie 22
myDate.getDay() // day of the week, where 0 means Sunday, 1 means monday, etc
myDate.getFullYear() // 4 digit year, ie, 2021
But I've always had to build a function to turn getDay into January, February, March, not anymore. toLocaleString() gives you some new superpowers. You can pass it two params, a string for region (ie, en-us) and an object with what you want back (ie, { month: 'long' }). This helps internationalize the response, if need be.
// Again, assuming myDate is a JS Date object...
myDate.toLocaleString('en-us', { month: 'long' } ) // March
Date Suffix I've still seen no built-in way to get the suffix for a date, like th, st, so I built this utility function that uses the modulus % operator to check the divisor of each day number and apply the right suffix (aimed at an American audience but might be the same elsewhere?).
/**
* setDateSuffix()
*
* Desc: Takes two digit date, adds 'st', 'nd', 'rd', etc
*
* #param { integer } num - a number date
*/
export const setDateSuffix = (num) => {
const j = num % 10,
k = num % 100
if (j === 1 && k !== 11) {
return num + "st";
}
if (j === 2 && k !== 12) {
return num + "nd";
}
if (j === 3 && k !== 13) {
return num + "rd";
}
return num + "th";
}
Altogether now.. Long winded way of getting here, but if I am given an ISO or Unix date and I want Month DDth, YYYY, this is what I run:
// setDateSuffix IS NOT PART OF BUILT-IN JS!
const newDate = new Date('23-12-2010')
const simpleDate = `${newDate.toLocaleString('en-us', { month: 'long' } )} ${setDateSuffix(newDate.getDate())}, ${newDate.getFullYear()}`
// yields: December 23rd, 2010
Note - all of this will likely change, hopefully for the better, when temporal becomes a reality in JS: https://github.com/tc39/proposal-temporal. Look forward to somebody's 2030 update of this post!

Categories

Resources