I have a date in format like that -
date= "2 march 2018"
I want to convert it to the format "20180302". i am using following method for that :
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
return [year, month, day].join('');
Everything works fine except that if my date has no date or month, it should return empty value in place of date and month. For example: If my date input is
date= "march 2018"
than, day = '' + d.getDate() should return empty. if date is "2018" than month = '' + (d.getMonth() + 1) and day = '' + d.getDate() should return null. I know it is a bad practise,but in my application I need to check if date and month is present of not..
var date= "2 march 2018";
var sp_date=date.split(" ");
var d = new Date(date);
if(sp_date.length==3){
month = '' + (d.getMonth() + 1);
day = '' + d.getDate();
year = d.getFullYear();
}else if(sp_date.length==2){
if(isNaN(Number(sp_date[0]))===false){
day = sp_date[0];
month='';
year=sp_date[1];
}else{
day ='';
month = '' + (d.getMonth() + 1);
year = d.getFullYear();
}
}else if(sp_date.length==1){
day ='';
month = '';
year = d.getFullYear();
}
return [year, month, day].join('');
You can do it with a single line using moment.js, Check the jsfiddle link below
http://jsfiddle.net/rLjQx/46813/
var date = moment("2 march 2018").format('YYYYMMDD');
Related
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
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');
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')
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);
}
I am trying to get tomorrow's date of a specific date using JavaScript in format (yyyy-mm-dd). For example the specific date is 2021-08-31 and I have got this script:
var date = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1],date.split("-")[2])
date.setDate(date.getDate() + 1);
var tomorrows_date_month = date.getMonth()
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)
The expected output is:
2021-09-01
But the output of this code is :
2021-9-2
First you don't need split "2021-08-31" to use as date parameter, so just use new Date("2021-08-31");
Second note that you need to use d.getMonth() + 1 and add leading zero if the length is less than 2:
Try this one:
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
Date.prototype.addDays = function(days) {
var date = new Date(this.valueOf());
date.setDate(date.getDate() + days);
return date;
}
var date = "2021-08-31"
var date1 = new Date(date);
console.log(formatDate(date1.addDays(1)));
Internally js month is stored as a value between 0 and 11. So you need to minusdate.split("-")[1] by 1. Otherwise, javascript will think that your month is actually September and we know that "2021-09-32" is translated to "2021-10-2", therefore the date is shown as "2".
var date = "2021-08-31"
date = new Date(date.split("-")[0],date.split("-")[1] - 1,date.split("-")[2])
date.setDate(date.getDate() + 1)
var tomorrows_date_month = date.getMonth() + 1
var tomorrows_date_day = date.getDate()
var tomorrows_date_year = date.getFullYear()
console.log(tomorrows_date_year + "-" + tomorrows_date_month + "-" + tomorrows_date_day)
Also note that date = new Date("2021-08-31") is enough for converting a string into a Date object.
new Date(new Date(date + 'T00:00Z').getTime() + 86400000).toISOString().substr(0, 10)
The added 'T00:00Z' assures the date is parsed as UTC, to match the UTC timezone used by toISOString(). Adding 86400000 (the number of milliseconds in one day) advances the date without having to fuss with the date field directly.
I have a requirement to validate start-date < end-date, but the date formats changes based on the regional settings.
User can change region of site at any time when user changes to different date formats by validation fails.
I get error if the format is of 19-2-1
function getFormattedDate(datestr) {
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return month + '/' + day + '/' + year;
}
//date format for all regions (mm-dd-yyyy, dd-mm-yyy, d mm yyyy, mm dd yyyy, mm/dd/yyyy, dd/mm/yyyy, dd.mm.yyyy, mm.dd.yyyy)
if (isNaN(StartDateEnfant.valueOf()) || isNaN(OData__EndDateEnfant.valueOf())) {
StartDateEnfant = new Date(startDate.replace(/(\d{2})[- /.](\d{2})[- /.](\d+)/, "$2/$1/$3"));
OData__EndDateEnfant = new Date(endDate.replace(/(\d{2})[- /.](\d{2})[- /.](\d+)/, "$2/$1/$3"));
}
I get wrong validation if start date is 3.1.2019(jan 3 2019) and end date if 10.1.2019 ( jan 10 2019) but it takes as sep 10 2019 which is wrong
I need to use JavaScript to covert a date to to from '2012-09-15T00:00:00' to a CCYYMMDD format? How can I do this?
I don't see what .NET and XSLT have to do with your question.
You could use the Date constructor to parse the ISO 8601 encoded string into a javascript Date object:
var dateStr = '2012-09-15T00:00:00';
var date = new Date(dateStr);
and then build the desired format:
var year = '' + date.getFullYear();
var month = date.getMonth() + 1;
month = month < 10 ? '0' + month : month;
var day = '' + date.getDate();
day = day < 10 ? '0' + day : day;
var formattedDate = year + month + day;
And here's a live demo.
Using replace and split.
var date = '2012-09-15T00:00:00';
date = date.replace(/-/,"").split("T")[0];// date will be 20120915
I have an string that contains month/date and I need to insert the year. The string looks like:
Last Mark:: 2/27 6:57 PM
I want to convert the string to something like:
Last Mark:: 2010/02/27 18:57
In this case, there will not be any entries more than a year old. For example, if the date were 10/12 it can be assumed that the year is 2009.
What is the best method for this?
Following from Adam's suggestion:
function convertDate(yourDate) {
var today = new Date();
var newDate = new Date(today.getFullYear() + '/' + yourDate);
// If newDate is in the future, subtract 1 from year
if (newDate > today)
newDate.setFullYear(newDate.getFullYear() - 1);
// Get the month and day value from newDate
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
// Add the 0 padding to months and days smaller than 10
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
// Return a string in YYYY/MM/DD HH:MM format
return newDate.getFullYear() + '/' +
month + '/' +
day + ' ' +
newDate.getHours() + ':' +
newDate.getMinutes();
}
convertDate('2/27 6:57 PM'); // Returns: "2010/02/27 18:57"
convertDate('3/27 6:57 PM'); // Returns: "2009/03/27 18:57"
the code for adding THIS year is simple
var d = Date();
var withYear = d.getFullYear() + yourDate;
however, the logic behind considerating if it should be this year or last year could be harder to do
I would think this way: get today's date. If the date is higher than today's, it's last year, so add d.getFullYear()-1, otherwise add d.getFullYear()
This returns the current year:
var d = new Date();
var year = d.getFullYear();
To figure whether its this year or not you could just compare the day and month with the current day and month, and if necessary, subtract 1 from the year.
To get the day and month from the Date object:
d.getMonth(); // warning this is 0-indexed (0-11)
d.getDate(); // this is 1-indexed (1-31)