This question already has answers here:
Where can I find documentation on formatting a date in JavaScript?
(39 answers)
Closed 9 years ago.
I have a function that gets a date from a jQuery calendar and then formats it in year-month-day.
The date I get for the calendar is 03/04/2013 for dateString and then I want it in the format of 2013-03-04. But the date I am getting for start_date is 2013-21-04. Strange because it had been ok, I think.
function makeUpDates() {
// concantenate values to date_start and date_end hidden inputs
var dateString = document.getElementById('date').value, date = new Date(dateString);
document.getElementById('date_start').value = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + ("0" + date.getDate()).slice(-2);
var numDays = document.getElementById('slider').value;
date.setDate(date.getDate() + parseInt(numDays));
var dateEnd = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + ("0" + date.getDate()).slice(-2);
document.getElementById('date_end').value = dateEnd;
}
You can convert the dates like this
//will take a date in the form MM/DD/YYYY and return YYYY-MM-DD
function convertDate(dateString){
var dateparts = dateString.split("/");
var newDate = dateparts[2]+"-"+dateparts[0]+"-"+dateparts[1]
return newDate;
}
Also for more general Date handling you can check out moment.js, mentioned in this answer to a more general question on this topic
start_date is 2013-21-04
Probably you forgot the parenthesis around date.getMonth()+1 in the string concatenation, yielding 21 instead of 3. It seems to be fixed in the snippet you posted though.
Related
This question already has answers here:
Javascript add leading zeroes to date
(30 answers)
How do I get Month and Date of JavaScript in 2 digit format?
(32 answers)
Javascript date - Leading 0 for days and months where applicable
(9 answers)
Closed 1 year ago.
I have one function that gives the date, the only problem is that my date is displayed like this on 5/31/2021, but I want to make it appear on 05/31/2021 here is my code
<span>{{ dtFormatter(course.updated_at) }}</span>
dtFormatter(d) {
var dateObj = new Date(d);
var day = dateObj.getUTCDate();
var month = dateObj.getUTCMonth() + 1; //months from 1-12
var year = dateObj.getUTCFullYear();
return day + "." + month + "." + year;
},
You can use padStart to add a leading Zero if needed:
day.padStart(2, '0') + '.' + month.padStart(2, '0') + '.' + year
day and month should be a string btw
You can use String#slice to add a leading 0 if needed:
('0' + day).slice(-2) + '.' + ('0' + month).slice(-2) + '.' + year;
Note: padStart doesn't work in IE.
I see you already calculated the day.
so you can do this.
`0${day}`.slice(-2)`
this will output 01~09 and 10~31.
As mentioned by #HassanImam, you could use a one-liner code:
new Date().toLocaleDateString('en-UK')
otherwise:
const date = new Date()
const m = String(date.getMonth() + 1).padStart(2, '0')
const d = String(date.getDate()).padStart(2, '0')
const y = String(date.getFullYear())
const formatedDate = [m, d, y].join('/')
console.log(formatedDate)
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 1 year ago.
how do i Get current date in Mon-DD-YYY format in JavaScript, i am trying to enter todays date without time in a date picker field
below is my current code and it is failing
Page.prototype.clickOnsessionDate = async function () {
const request = await this.findByXpath(clickOnsessionDate);
await this.write(reques, Date());
await this.driver.sleep(5000);
};
You could do this:
var date = new Date();
alert(((date.getMonth() > 8) ? (date.getMonth() + 1) : ('0' + (date.getMonth() + 1))) + '/' + ((date.getDate() > 9) ? date.getDate() : ('0' + date.getDate())) + '/' + date.getFullYear());
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I have a simple problem. i need to get only the date as string and remove its time.
How can i do this? I tried new Date() but its not working.
const value = '2018-04-09 00:00:00'
You can try this
const currentDate = new Date();
const formattedDate = ''
+ currentDate.getDate().toString().padStart(2, '0') + '-'
+ (currentDate.getMonth() + 1).toString().padStart(2, '0') + '-'
+ currentDate.getFullYear();
console.log(formattedDate)
// output
"09-05-2019"
function yyyymmdd(date) {
var mm = date.getMonth() + 1; // getMonth() is zero-based
var dd = date.getDate();
return [date.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('-');
};
let date=new Date()
console.log(yyyymmdd(date))
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
I've got multiple dictionaries with dates in and I need to find the highest one. To compare the dates I get the date from the dictionary, convert it using new Date(dateString) to be able to compare the dates to get the latest date.
The dateString looks like this: 2019-03-07 08:40:16
I convert this using new Date(dateString) and it looks like this:
Thu Mar 07 2019 08:40:16 GMT+0000 (Greenwich Mean Time)
I then need to convert it back to original format YYYY-MM-DD HH:MM:SS
What is the best way to do this, I thought there would be something where you could define the output format for new Date() but can't find anything.
Any help is appreciated.
I'd recommend you to use Moment https://momentjs.com/ lib for time comparison and formatting.
const date1 = moment('2019-03-06 08:40:16', 'YYYY-MM-DD HH:mm:ss');
const date2 = moment('2019-03-07 08:40:16', 'YYYY-MM-DD HH:mm:ss');
const isBefore = date1.isBefore(date2);
console.log('isBefore', isBefore);
console.log('formatted date:', date2.format('YYYY-MM-DD HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
This is surely ain't the most elegant solution but based on the conversion from dateString, you can reconstruct it using the Date() objects built-in methods.
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
var temp2 = "" + temp.getFullYear() + "-" + (temp.getMonth() + 1) + "-" + temp.getDate() + " " + temp.getHours() + ":" + temp.getMinutes() + ":" + temp.getSeconds();
console.log(temp2);
If you plan to do this with multiple dates, you might consider enhancing the Date object with your own method like:
Date.prototype.reformat = function() {
return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate() + " " + this.getHours() + ":" + this.getMinutes() + "." + this.getSeconds();
}
var dateString = "2019-03-07 08:40:16";
var temp = new Date(dateString);
console.log(temp.reformat());
This question already has answers here:
How to add number of days to today's date? [duplicate]
(16 answers)
Closed 8 years ago.
i have the date 2013-12-28 and i want add one or more more day to it. so if i add one more day it will be 2013-12-29.
i try to add it by adding the value of it's date (date 28+1), it works, but what if i add 7 more day to it? the date will be 35, and of course it is not a valid date format.
can someone help me?
here's the example of my script:
var d = new Date();
var Y = d.getFullYear();
var M = d.getMonth()+1;
var D = d.getDate();
var DT = d.getDate()+1;// what if i + 20 days from today? the format would be invalid
var today = Y+"-"+M+"-"+D;
var tomorrow = Y+"-"+M+"-"+DT;
alert(today+" <> "+tomorrow);
// "<>" means nothing
You may try like this using getdate(), setdate() and getdate():
var myDate = new Date();
myDate.setDate(myDate.getDate() + 7);
If you already have a date object as in the code you show:
var d = new Date();
...then you can add 7 days to it like this:
d.setDate( d.getDate() + 7 );
...and it will automatically increment the month if needed.
Further reading:
The Date object
.getDate() method
.setDate() method
If you need to extract the year, month and day in order to format the result a particular way do so after adding days.
The solution is to convert your date string into unix timestamp, and them add 3600 * 24 * <number of days> to the timestamp and them convert it back to date string.
The code can be as follows:
function addDaysToDate(date, days) {
var time = Date.parse(date) + days * 24 * 3600;
date = new Date(time);
return date.getFullYear() + '-' + date.getMonth() + '-' + date.getDate();
}
var date = '2013-12-28';
console.log(addDaysToDate(date, 7));