Javascript convert date string to object [duplicate] - javascript

This question already has answers here:
Parsing a string to a date in JavaScript
(35 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 4 years ago.
I'm trying to convert a date in string format to a Date object in JavaScript. The date is coming from the openweathermap.org API, which gives the date string in the following format:
'2018-04-28 09:00:00' or 'yyyy-mm-dd hh:mm:ss'
I know that the JavaScript Date class can take other string formats of dates, but this one returns NaN when I try anything with it. How can I convert a date string, like the one above, and convert it easily to a JavaScript object? Thanks!

Since you are getting NaN while directly converting the string to date. You can split the string on spaces, - and : and then pass the value to date constructor and generate the date object.
const str = `2018-04-28 09:00:00`;
const [date, time] = str.split(' ');
const [year, month, day] = date.split('-');
const [hh, mm, sec] = time.split(':');
const dateObj = new Date(year, month - 1, day, hh, mm, sec);
console.log(dateObj);
As pointed out by #RobG, this could also be done using the regex.
const str = `2018-04-28 09:00:00`;
var b = str.split(/\D/);
var date = new Date(b[0],b[1]-1,b[2],b[3],b[4],b[5]);
console.log(date);
const str = `2018-04-28 09:00:00`,
date = new Date(...(str.split(/\D/).map((v,i)=>i==1?--v:v)));
console.log(date);

Just try new Date(str)
d = new Date("2018-04-20 09:00:00")
Fri Apr 20 2018 09:00:00 GMT+0800 (Hong Kong Standard Time)
d.getDate()
20
ref: https://www.ecma-international.org/ecma-262/6.0/#sec-date-time-string-format

Related

Create Date object passing a date format of mmddyyyy [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 10 months ago.
I'm trying to create a date with the format 'mmddyyyy'. I've noticed I can pass a four digit string, but when I use the format above, it says invalid date. How can I go about this with pure js?
let dateString = '01012022'
let d = new Date(dateString)
maybe you want something like that
let dateString = '01012022'
let [match, dd, mm, yyyy] = dateString.match(/(\d{2})(\d{2})(\d{4})/)
// iso format
let d = new Date(`${yyyy}${mm}${dd}`)
Seems like you have to split your string into pieces then use common Date() constructor with separated day, month and year
//Your string with date
let dateString = '01012022';
//extracting 2 first numbers as m (month), 2 second as d (day) and the last 4 as y (year)
let {d,m,y} = /(?<m>\d{2})(?<d>\d{2})(?<y>\d{4})/.exec(dateString).groups;
//then create new date using constructor
let date = new Date(y,m,d);

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)

Convert Date string to Object with current timezone format [duplicate]

This question already has answers here:
How to convert dd/mm/yyyy string into JavaScript Date object? [duplicate]
(10 answers)
Closed 2 years ago.
I have this code to add a reminder to a calendar
function addCalendarEvent(eventDate, eventTitle){
let dateObj = new Date(eventDate);
let calendarId = "me#gmail.com";
let cal = CalendarApp.getCalendarById(calendarId);
let event = cal.createAllDayEvent(eventTitle, dateObj)
event.addEmailReminder(420)
}
The eventDate is passed into the function as a string in the format dd/MM/YYYY but the output from let dateObj = new Date(eventDate); is in american format. ie. 02/10/2020 comes out as Mon Feb 10 2020 00:00:00 GMT+0000 (Greenwich Mean Time). Any help correcting this would be great. Dates give me an absolute headache
In the end I decided that just working with date objects from the off would be easiest
This will give you the date object of the string in the format dd/MM/YYYY
function ddmmyyyytFormatterWithTime(date) {
var dateDiv = date.split('/');
var date = new Date();
date.setDate(dateDiv[0]);
date.setMonth(--dateDiv[1]); // -- since it starts from 0
date.setFullYear(dateDiv[2]--);
return date;
};
function ddmmyyyytFormatter(date) {
var dateDiv = date.split('/');
var date = new Date();
date.setHours(0, 0, 0, 0); // to reset time
date.setDate(dateDiv[0]);
date.setMonth(--dateDiv[1]); // -- since it starts from 0
date.setFullYear(dateDiv[2]);
return date;
};
var date = ddmmyyyytFormatter("10/02/2020");
var dateWithTime = ddmmyyyytFormatterWithTime("10/02/2020");

new Date() always read dd/mm/yyyy as mm/dd/yyyy(month first) hence day and month values get mixed resulting in NaN/Error [duplicate]

This question already has answers here:
How to convert dd/mm/yyyy string into JavaScript Date object? [duplicate]
(10 answers)
Why does Date.parse give incorrect results?
(11 answers)
Closed 3 years ago.
When converting date for example:
var dateObj = new Date("10/01/2019");
console.log(dateObj);
returns Tue Oct 01 2019 00:00:00 i.e. it takes in the day as month and likewise with the month value
How to make new Date() to take dd/mm/yyyy ??
Answer is here: https://stackoverflow.com/a/33299764/6664779
(From original answer) We can use split function and then join up the parts to create a new date object:
var dateString = "23/10/2019"; // Oct 23
var dateParts = dateString.split("/");
// month is 0-based, that's why we need dataParts[1] - 1
var dateObject = new Date(+dateParts[2], dateParts[1] - 1, +dateParts[0]);
document.body.innerHTML = dateObject.toString();

How to convert date to milliseconds by javascript? [duplicate]

This question already has answers here:
How do I get a timestamp in JavaScript?
(43 answers)
Closed 4 years ago.
I have multiple date's for example(25-12-2017) i need them to be converted to milliseconds by javascript
One way is to use year, month and day as parameters on new Date
new Date(year, month [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
You can prepare your date string by using a function.
Note: Month is 0-11, that is why m-1
Here is a snippet:
function prepareDate(d) {
[d, m, y] = d.split("-"); //Split the string
return [y, m - 1, d]; //Return as an array with y,m,d sequence
}
let str = "25-12-2017";
let d = new Date(...prepareDate(str));
console.log(d.getTime());
Doc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
var dateTokens = "2018-03-13".split("-");
//creating date object from specified year, month, and day
var date1 = new Date(dateTokens[0], dateTokens[1] - 1, dateTokens[2]);
//creating date object from specified date string
var date2 = new Date("2018-03-13");
console.log("Date1 in milliseconds: ", date1.getTime());
console.log("Date2 in milliseconds: ", date1.getTime());
console.log("Date1: ", date1.toString());
console.log("Date2: ", date2.toString());
In addition to using vanilla javascript, you can also use many libraries to get more functions.
like date-fns, moment.js etc
For example, use moment.js you can convert date to milliseconds by moment('25-12-2017', 'DD-MM-YYYY').valueOf(), more elegant and powerful than vanilla javascript.

Categories

Resources