I have a date formatted as string, eg: 240800. The date format for that string is YYMMDD. With the below code, I can convert the string to date but it doesn't always work in deducting 1 day. I need my output to be a valid date, not with 00 day. So with the date above, it should be converted and formatted to 07/31/2024.
Here's what I got so far.
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var date = new Date('20' year, month, day);
var formattedDate = date.getMonth() '/' date.getDate() '/' date.getFullYear();
console.log(formattedDate);
}
Working:
"240800" = 7/31/2024
All months from 4 to 12
Not Working:
"240100" = 0/31/2024 x
"240200" = 1/29/2024 x
"240300" = 2/31/2024 x
CodePudding user response:
The reason is the date
variable parameter in new Date()
is counted as 0~11, not the general range,1~12.
So the working answer actually is wrong. It seems like being right
just for July and August have 31 days.
The correct way is to firstly deduct 1 month and then calculate it. After all of the process is done, you can add 1 month in the end.
The below is working codes:
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
//deduct 1 month firstly
var month = Number(stringDate.substring(2,4))-1;
var day = stringDate.substring(4,6);
var date = new Date('20' year, month, day);
//add 1 month finally
var formattedDate = date.getMonth() 1 '/' date.getDate() '/' date.getFullYear();
console.log(formattedDate);
}
formatDate('240100');
CodePudding user response:
In python Assuming your string is yymmdd below function should do what you want. I am sure javascript has some module for date handling.
from datetime import datetime, timedelta
def fd(s):
d=datetime.strptime(s[:-2],'%y%m') timedelta(days=int(s[-2:])-1)
return d.strftime('%m/%d/%Y')
CodePudding user response:
Try this ..
function formatDate(stringDate) {
var year = stringDate.substring(0,2);
var month = stringDate.substring(2,4);
var day = stringDate.substring(4,6);
var d1;
if (day==="00")
{
d1 = new Date(month '/01/20' year);
d1.setDate(d1.getDate() -1);
//console.log("day1" d1);
}
else
{
d1 = new Date('20' year, month, day);
}
var formattedDate = d1.getMonth() '/' d1.getDate() '/' d1.getFullYear();
console.log(formattedDate);
}