How to convert "dd/mm/yyyy" to ISO string in JavaScript - javascript

How can I convert this date: 29/12/2022 where:
29 is day,
12 is month,
2022 is year,
to ISO string.
I tried this:
var dateStr = "29/12/2022";
var parts = dateStr.split("/")
var myDate = new Date(parseInt(parts[2]), parseInt(parts[1]) - 1, parseInt(parts[0]));
console.log(myDate.toISOString());
// 2024-05-11T22:00:00.000Z this is wrong
I was expecting different result.

There is no need to parseInt and to remove 1 to the month.
var dateStr = "29/12/2022";
var parts = dateStr.split("/")
var myDate = new Date(`${parts[2]}-${parts[1]}-${parts[0]}`);
console.log(myDate.toISOString());

In my code usually I do something like this:
const dateStr = "29/12/2022";
const parts = dateStr.split("/");
const date = new Date(0); // It will set hours, minutes, and seconds to 0
date.setDate(parts[0]);
date.setMonth(parts[1]-1);
date.setFullYear(parts[2]);
console.log(date.toISOString());

It may not be the most optimal way but you could do it this way as long as the month when it is a single digit is sent with zero at the beginning type: 01 -> January
let date = '29/12/2022';
let dateFormat = date[3]+date[4]+"-"+date[0]+date[1]+"-
"+date[6]+date[7]+date[8]+date[9]
// 12-29-2022
let mydate = new Date(dateFormat)
// Thu Dec 29 2022 00:00:00 GMT-0500

Related

getDay () unexpected output on the last day of the month

I have a script that gives me the days of the week, when I enter the day from 1 to 30 there are no problems, but when I enter the 31st, the script returns the first day of the same month.
function myFunction() {
let numDayOfMonth = 31;
const arrayDayWeek = ['Su','Mo','Tu','We','Th','Fr','Sa'];
let initialDate = new Date();
initialDate.setDate(numDayOfMonth);
initialDate.setMonth(4);
const numDayOfWeek = initialDate.getDay();
console.log(initialDate);
const nameDayOfWeek = arrayDayWeek[numDayOfWeek];
return nameDayOfWeek;
}
Current output
Sat May 01 2021 20:40:48 GMT-0500 (Colombia Standard Time)
Expected output
Mo May 31 2021 20:40:48 GMT-0500 (Colombia Standard Time)
new Date() would use today's date initially, so that would be 15th June 2021. When you then try to set the Day to the 31st it wraps back to 01 because June only has 30 days.
To get your expected output you should set the Month first.
Your code is working as expected. I will explain.
function myFunction() {
let numDayOfMonth = 31;
const arrayDayWeek = ['Su','Mo','Tu','We','Th','Fr','Sa'];
let initialDate = new Date(); // initialDate will be 15/06/2021
initialDate.setDate(numDayOfMonth); // initialDate will be 01/07/2021, because 31/06/2021 doesn't exist
initialDate.setMonth(4); // initialDate will be 01/05/2021
const numDayOfWeek = initialDate.getDay();
console.log(initialDate);
const nameDayOfWeek = arrayDayWeek[numDayOfWeek];
return nameDayOfWeek;
}
This is happening because you are setting the day first, then the month, which means you are setting it to the 31st day of the current month. If the current month has 30 days, it will roll over to 1.
Instead, use the constructor to specify the values:
function myFunction() {
let numDayOfMonth = 31;
const arrayDayWeek = ['Su','Mo','Tu','We','Th','Fr','Sa'];
const today = new Date();
const initialDate = new Date(today.getFullYear(), 4, numDayOfMonth);
const numDayOfWeek = initialDate.getDay();
console.log(initialDate.toLocaleString());
const nameDayOfWeek = arrayDayWeek[numDayOfWeek];
return nameDayOfWeek;
}
myFunction();

add 12 months for Now Date

Hi, I would like to add 12 months and subtract 1 day for my current
date.
Example :
valStartDate :2018-01-20
expected_date:2019-01-19
I try below code but error "getFullYear() not a function to allow"
this.endDate =this.valStartDate.getFullYear()+1+'-'+this.valStartDate.getMonth()+'-'+(this.valStartDate.getDate()-1);
Ensure that your given start date is a date and not a string.
var startDate = new Date(2018, 0, 20);
var startDatePlus12Months = new Date(startDate.setMonth(startDate.getMonth() + 12));
var expectedDate = new Date(startDatePlus12Months.getFullYear(), startDatePlus12Months.getMonth(), startDatePlus12Months.getDate() - 1);
Here is a method of abstracting the date you want, apply this the variable and you should be good to go.
var date = new Date(); // now
var newDate = new Date(date.getFullYear() + 1, date.getMonth(), date.getDate() - 1);
console.log(newDate.toLocaleDateString());
this.valStartDate.getFullYear() In order for this to work, this.valStartDate must be a valid javascript date and look the same format as new Date(); would give you.
Fri Apr 26 2019 11:52:15 GMT+0100 (British Summer Time)
this.endDate = new Date(this.endDate); // <= maybe you get a string date...
this.endDate.setMonth(this.endDate.getMonth() + 12);
this.endDate.setDate(this.endDate.getDate() - 1);
If you're getting your date from a server or from a previous Json format, maybe you need to convert it from string to Date first: this.endDate = new Date(this.endDate);. It seems this is your case.
This is easy with the help of Moment.js:
const startDate = moment('2018-01-20');
const endDate = startDate.add(12, 'months').subtract(1, 'days').toDate();

Tricky date string to parse in JavaScript

Fri Nov 10 05:45:36 +0000 2017
I've tried both moment and chrono-node. Both are getting stumped by this date format.
Any suggestions to get a valid UTC date?
Thanks
To add to #CertainPerformance's answer, the problem with your code, if you try with MomentJS is that it is not a standard ISO date string. Parsing it directly without specifying format will result in incorrect result and a warning like this:
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 and will be removed in an upcoming major release.
To mitigate, always pass the format to MomentJS constructor like this:
const inputStr = "Fri Nov 10 05:45:36 +0000 2017"
const mom = moment(inputStr, 'ddd MMM D HH:mm:ss ZZ YYYY');
console.log(mom.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
I think this should help you out:
var date = new Date("Fri Nov 10 05:45:36 +0000 2017").toISOString();
date = date.split("T")[0];
console.log(date);
Moment works just fine:
const inputStr = "Fri Nov 10 05:45:36 +0000 2017"
const mom = moment(inputStr, 'ddd MMM D HH:mm:ss ZZ YYYY');
console.log(mom.toISOString());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
You can see the difference between 2 items of each array which is returned by the code that I have written to process the date strings of the form you have provided.
Finally you can have a look at the full code example given.
In first case, both are same.
In second case, both are different.
console.log(dateArr1); // [ '2017-11-10', '2017-11-10' ];
console.log(dateArr2); // [ '2018-05-15', '2018-05-14' ];
So it's clear our UTC conversion is working fine.
Please have a look at the below code example and try to understand. It is simple.
NoteĀ» All the comments inside function are for inputDateStr: "Fri Nov 10 05:45:36 +0000 2017"
// All the comments inside function are for
// inputDateStr: "Fri Nov 10 05:45:36 +0000 2017"
function getMyUTCDate(inputDateStr)
{
var inputDateString = inputDateStr;
var date = new Date(inputDateString);
var dateArr = []; // To store 2 dates, simple one & full UTC one
console.log(date); // 2017-11-10T05:45:36.000Z
// ............... SIMPLE EXAMPLE ..........................
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes()
var seconds = date.getSeconds();
console.log(year); // 2017
console.log(month); // 10
console.log(day); // 10
console.log(hours); // 11
console.log(minutes); // 15
console.log(seconds); // 36
utcDate = new Date(Date.UTC(year, month, day, hours, minutes, seconds));
utcDateString = utcDate.toUTCString();
console.log(utcDate); // 2017-11-10T11:15:36.000Z
console.log(utcDateString); // Fri, 10 Nov 2017 11:15:36 GMT
var dt1 = utcDate.toISOString().split('T')[0]
dateArr.push(dt1)
console.log(dt1); // 2017-11-10
// .................. FULL UTC EXAMPLE ..........................
var utcYear = date.getUTCFullYear();
var utcMonth = date.getUTCMonth();
var utcDay = date.getUTCDate();
var utcHours = date.getUTCHours();
var utcMinutes = date.getUTCMinutes()
var utcSeconds = date.getUTCSeconds();
console.log(utcYear); // 2017
console.log(utcMonth); // 10
console.log(utcDay); // 10
console.log(utcHours); // 5
console.log(utcMinutes);// 45
console.log(utcSeconds);// 36
var utcDate2 = new Date(Date.UTC(utcYear, utcMonth, utcDay, utcHours, utcMinutes, utcSeconds));
var utcDateString2 = utcDate2.toUTCString();
console.log(utcDate2); // 2017-11-10T05:45:36.000Z
console.log(utcDateString2); // Fri, 10 Nov 2017 05:45:36 GMT
// Get UTC Date
var dt2 = utcDate2.toISOString().split('T')[0]
dateArr.push(dt2)
console.log(dt2); // 2017-11-10
return dateArr;
}
// Inputs
var inputDateString1 = "Fri Nov 10 05:45:36 +0000 2017";
var inputDateString2 = "Mon May 14 23:59:36 +0000 2018";
var dateArr1 = getMyUTCDate(inputDateString1);
var dateArr2 = getMyUTCDate(inputDateString2);
// Print dates
console.log(dateArr1); // [ '2017-11-10', '2017-11-10' ]
console.log(dateArr2); // [ '2018-05-15', '2018-05-14' ]
References
developer.mozilla.org - Date processing functions
Thanks.

DateTime new Date(params) in javascript is faster by 1 month

It is very weird but it seems that new Date(params), when passed in the correct format of year, month, day, hours, minutes, seconds, milliseconds, it is ahead by 1 month.
Take a look at the following implementation:
// The format below needs to be changed according to req.param('dateTime')
// dateTime format is as follows: "dd/MM/yyyy HH:mm:ss"
var dateTime = report['dateTime'];
console.log('dateTime: '+dateTime);
var dateTimeSplit = dateTime.split(' ');
var dateSplit = dateTimeSplit[0].split('/');
var timeSplit = dateTimeSplit[1].split(':');
var day = parseInt(dateSplit[0]);
var month = parseInt(dateSplit[1]);
var year = parseInt(dateSplit[2]);
var hour = parseInt(timeSplit[0]);
var minute = parseInt(timeSplit[1]);
var second = parseInt(timeSplit[2]);
var createdAt = new Date(year, month, day, hour, minute, second, 0);
console.log('createdAt: '+createdAt);
And the results from the logs are:
Feb 09 04:13:46 sails-wusrs app/web.1: createdAt: Mon Mar 09 2015 12:02:24 GMT+0000 (UTC)
Feb 09 04:13:46 sails-wusrs app/web.1: dateTime: 09/02/2015 12:02:24
This server is running on heroku and it's weird that the log of createdAt is in front of dateTime. Everything else is alright, except for the month. 02 is Feb right? I'm so confused. Thanks for any help!
Month in javascript datetime starts from 0.
http://javascript.info/tutorial/datetime-functions

javascript: get month/year/day from unix timestamp

I have a unix timestamp, e.g., 1313564400000.00. How do I convert it into Date object and get month/year/day accordingly? The following won't work:
function getdhm(timestamp) {
var date = Date.parse(timestamp);
var month = date.getMonth();
var day = date.getDay();
var year = date.getYear();
var formattedTime = month + '/' + day + '/' + year;
return formattedTime;
}
var date = new Date(1313564400000);
var month = date.getMonth();
etc.
This will be in the user's browser's local time.
An old question, but none of the answers seemed complete, and an update for 2020:
For example: (you may have a decimal if using microsecond precision, e.g. performance.now())
let timestamp = 1586438912345.67;
And we have:
var date = new Date(timestamp); // Thu Apr 09 2020 14:28:32 GMT+0100 (British Summer Time)
let year = date.getFullYear(); // 2020
let month = date.getMonth() + 1; // 4 (note zero index: Jan = 0, Dec = 11)
let day = date.getDate(); // 9
And if you'd like the month and day to always be a two-digit string (e.g. "01"):
let month = (date.getMonth() + 1).toString().padStart(2, '0'); // "04"
let day = date.getDate().toString().padStart(2, '0'); // "09"
For extended completeness:
let hour = date.getHours(); // 14
let minute = date.getMinutes(); // 28
let second = date.getSeconds(); // 32
let millisecond = date.getMilliseconds(); // 345
let epoch = date.getTime(); // 1586438912345 (Milliseconds since Epoch time)
Further, if your timestamp is actually a string to start (maybe from a JSON object, for example):
var date = new Date(parseFloat(timestamp));
or for right now:
var date = new Date(Date.now());
More info if you want it here (2017).
Instead of using parse, which is used to convert a date string to a Date, just pass it into the Date constructor:
var date = new Date(timestamp);
Make sure your timestamp is a Number, of course.

Categories

Resources