Normally if I wanted to get the date I could just do something like
var d = new Date();
console.log(d);
The problem with doing that, is when I run that code, it returns:
Mon Aug 24 2015 4:20:00 GMT-0800 (Pacific Standard Time)
How could I get the Date() method to return a value in a "MM-DD-YYYY" format so it would return something like:
8/24/2015
Or, maybe MM-DD-YYYY H:M
8/24/2016 4:20
Just use the built-in .toISOString() method like so: toISOString().split('T')[0]. Simple, clean and all in a single line.
var date = (new Date()).toISOString().split('T')[0];
document.getElementById('date').innerHTML = date;
<div id="date"></div>
Please note that the timezone of the formatted string is UTC rather than local time.
The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:
var todaysDate = new Date();
function convertDate(date) {
var yyyy = date.getFullYear().toString();
var mm = (date.getMonth()+1).toString();
var dd = date.getDate().toString();
var mmChars = mm.split('');
var ddChars = dd.split('');
return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}
console.log(convertDate(todaysDate)); // Returns: 2015-08-25
Yet another way:
var today = new Date().getFullYear()+'-'+("0"+(new Date().getMonth()+1)).slice(-2)+'-'+("0"+new Date().getDate()).slice(-2)
document.getElementById("today").innerHTML = today
<div id="today">
By using Moment.js library, you can do:
var datetime = new Date("2015-09-17 15:00:00");
datetime = moment(datetime).format("YYYY-MM-DD");
var today = new Date();
function formatDate(date) {
var dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear();
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
//return dd + '/' + mm + '/' + yyyy;
return yyyy + '/' + mm + '/' +dd ;
}
console.log(formatDate(today));
function formatdate(userDate){
var omar= new Date(userDate);
y = omar.getFullYear().toString();
m = omar.getMonth().toString();
d = omar.getDate().toString();
omar=y+m+d;
return omar;
}
console.log(formatDate("12/31/2014"));
What you want to achieve can be accomplished with native JavaScript. The object Date has methods that generate exactly the output you wish.
Here are code examples:
var d = new Date();
console.log(d);
>>> Sun Jan 28 2018 08:28:04 GMT+0000 (GMT)
console.log(d.toLocaleDateString());
>>> 1/28/2018
console.log(d.toLocaleString());
>>> 1/28/2018, 8:28:04 AM
There is really no need to reinvent the wheel.
If you are trying to get the 'local-ISO' date string. Try the code below.
function (date) {
return new Date(+date - date.getTimezoneOffset() * 60 * 1000).toISOString().split(/[TZ]/).slice(0, 2).join(' ');
}
+date Get milliseconds from a date.
Ref: Date.prototype.getTimezoneOffset
Have fun with it :)
Here is a simple function I created when once I kept working on a project where I constantly needed to get today, yesterday, and tomorrow's date in this format.
function returnYYYYMMDD(numFromToday = 0){
let d = new Date();
d.setDate(d.getDate() + numFromToday);
const month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1;
const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate();
return `${d.getFullYear()}-${month}-${day}`;
}
console.log(returnYYYYMMDD(-1)); // returns yesterday
console.log(returnYYYYMMDD()); // returns today
console.log(returnYYYYMMDD(1)); // returns tomorrow
Can easily be modified to pass it a date instead, but here you pass a number and it will return that many days from today.
If you're not opposed to adding a small library, Date-Mirror (NPM or unpkg) allows you to format an existing date in YYYY-MM-DD into whatever date string format you'd like.
date('n/j/Y', '2020-02-07') // 2/7/2020
date('n/j/Y g:iA', '2020-02-07 4:45PM') // 2/7/2020 4:45PM
date('n/j [until] n/j', '2020-02-07', '2020-02-08') // 2/7 until 2/8
Disclaimer: I developed Date-Mirror.
This will convert a unix timestamp to local date (+ time)
function UnixTimeToLocalDate = function( unix_epoch_time )
{
var date,
str;
date = new Date( unix_epoch_time * 1000 );
str = date.getFullYear() + '-' +
(date.getMonth() + 1 + '').padStart( 2, '0' ) + '-' +
(date.getDate() + '').padStart( 2, '0' );
// If you need hh:mm:ss too then
str += ' ' +
(date.getHours() + '').padStart( 2, '0' ) + ':' +
(date.getMinutes() + '').padStart( 2, '0' ) + ':' +
(date.getSeconds() + '').padStart( 2, '0' );
return str;
}
If you want a text format that's good for sorting use:
function formatDateYYYYMMDDHHMMSS(date){
// YYYY-MM-DD HH:MM:SS
const datePart = date.toISOString().split("T")[0]
const timePart = date.toLocaleString('en-US', {hour12: false}).split(",")[1]
return datePart + timePart
}
As prototype:
Date.prototype.toSortString = function(){
const date = new Date(this.valueOf());
return date.toISOString().split("T")[0] +
date.toLocaleString('en-US', {hour12: false}).split(",")[1]
}
Simple one line elegant solution for fullYear-fullMonth-FullDay as '2000-01-01'
new Date().toLocaleDateString("fr-CA",
{year:"numeric", month: "2-digit", day:"2-digit"}
)
const padTo2Digits = num => {
return num.toString().padStart(2, '0')
}
const formatDate = date => {
return [
date.getFullYear(),
padTo2Digits(date.getMonth() + 1),
padTo2Digits(date.getDate())
].join('-')
}
let value = formatDate(new Date())
document.getElementById('dayFormatUS').innerHTML = value
const transformDate = date => {
const convert = date.split('-').reverse()
return convert.join('/')
}
document.getElementById('dayFormatBR').innerHTML = transformDate(value)
<div>
Format US -
<span id='dayFormatUS'></span>
</div>
<div>
Format BR -
<span id='dayFormatBR'></span>
</div>
I am trying to add days to a given date using Javascript. I have the following code:
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var joindate = new Date(datepicker);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
On first alert I get the date 24/06/2011 but on second alert I get Thu Dec 06 2012 00:00:00 GMT+0500 (Pakistan Standard Time) which is wrong I want it to remain 24/06/2011 so that I can add days to it. In my code I want my final output to be 25/06/2011.
Fiddle is # http://jsfiddle.net/tassadaque/rEe4v/
Date('string') will attempt to parse the string as m/d/yyyy. The string 24/06/2011 thus becomes Dec 6, 2012. Reason: 24 is treated as a month... 1 => January 2011, 13 => January 2012 hence 24 => December 2012. I hope you understand what I mean. So:
var dmy = "24/06/2011".split("/"); // "24/06/2011" should be pulled from $("#DatePicker").val() instead
var joindate = new Date(
parseInt(dmy[2], 10),
parseInt(dmy[1], 10) - 1,
parseInt(dmy[0], 10)
);
alert(joindate); // Fri Jun 24 2011 00:00:00 GMT+0500 (West Asia Standard Time)
joindate.setDate(joindate.getDate() + 1); // substitute 1 with actual number of days to add
alert(joindate); // Sat Jun 25 2011 00:00:00 GMT+0500 (West Asia Standard Time)
alert(
("0" + joindate.getDate()).slice(-2) + "/" +
("0" + (joindate.getMonth() + 1)).slice(-2) + "/" +
joindate.getFullYear()
);
Demo here
I would like to encourage you to use DateJS library. It is really awesome!
function onChange(e) {
var date = Date.parse($("#DatePicker").val()); //You might want to tweak this to as per your needs.
var new_date = date.add(n).days();
$('.new').val(new_date.toString('M/d/yyyy'); //You might want to tweak this as per your needs as well.
}
Assuming numberOfDaysToAdd is a number:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
The first alert is the value of the field. the second is the generated date from a non-US formatted date.
Here is a working example (seems that this kind of markup is necessary to get noticed)
If you want to keep your code, then you need to change
var joindate = new Date(datepicker);
to
var parms = datepicker.split("/");
then use
var joindate = new Date(parms[1]+"/"+parms[0]+"/"+parms[2]);
OR the identically working
var joindate = new Date(parms[2],parms[1]-1,parms[0]);
As pointed out in a few other answers too, use the .getDate()
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
Lastly you want to add a 0 if the month is < 10
if (mm<10) mm="0"+mm;
If you are using the datepicker from jQuery UI, then you can do
$('.new').val($("#DatePicker").datepicker( "setDate" , +1 ).val());
instead of your function
http://jqueryui.com/demos/datepicker/#method-setDate
Sets the current date for the
datepicker. The new date may be a Date
object or a string in the current date
format (e.g. '01/26/2009'), a number
of days from today (e.g. +7) or a
string of values and periods ('y' for
years, 'm' for months, 'w' for weeks,
'd' for days, e.g. '+1m +7d'), or null
to clear the selected date.
Try
function onChange(e) {
var datepicker = $("#DatePicker").val();
alert(datepicker);
var parts = datepicker.split(/[^\d]/);
var joindate = new Date();
joindate.setFullYear(parts[2], parts[1]-1, parts[0]);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
I suppose the problem is JavaScript expects format MM/DD/YYYY not DD/MM/YYYY when passed into Date constructor.
To answer your real problem, I think your issue is that you're trying to parse the text-value of the DatePicker, when that's not in the right format for your locale.
Instead of .val(), use:
var joindate = $('#DatePicker').datepicker("getDate");
to get the underyling Date() object representing the selected date directly from jQuery.
This guarantees that the date object is correct regardless of the date format specified in the DatePicker or the current locale.
Then use:
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
to move it on.
Is it a typo round joindate.setDate(joindate + numberOfDaysToAdd)?
I tried this code, it seems ok to me
var joindate = new Date(2010, 5, 24);
alert(joindate);
var numberOfDaysToAdd = 1;
joindate.setDate(joindate.getDate() + numberOfDaysToAdd);
var dd = joindate.getDate();
var mm = joindate.getMonth() + 1;
var y = joindate.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
alert(joinFormattedDate);
Date.prototype.addDays = function(days) {
this.setDate(this.getDate() + days);
return this;
};
and in your javascript code you could call
var currentDate = new Date();
// to add 8 days to current date
currentDate.addDays(8);
function onChange(e) {
var datepicker = $("#DatePicker").val().split("/");
var joindate = new Date();
var numberOfDaysToAdd = 1;
joindate.setFullYear(parseInt(datepicker[2]), parseInt(datepicker[1])-1, parseInt(datepicker[0])+numberOfDaysToAdd);
$('.new').val(joindate);
}
http://jsfiddle.net/roberkules/k4GM5/
try this.
Date.prototype.addDay = function(numberOfDaysToAdd){
this.setTime(this.getTime() + (numberOfDaysToAdd * 86400000));
};
function onChange(e) {
var date = new Date(Date.parse($("#DatePicker").val()));
date.addDay(1);
var dd = date.getDate();
var mm = date.getMonth() + 1;
var y = date.getFullYear();
var joinFormattedDate = dd + '/' + mm + '/' + y;
$('.new').val(joinFormattedDate);
}
I've created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();
I need to have the date appear with leading zeroes on the day and month component by way of adding these rules to the script. I can't seem to get it to work.
if (MyDate.getMonth < 10)getMonth = '0' + getMonth;
and
if (MyDate.getDate <10)get.Date = '0' + getDate;
If someone could show me where to insert these into the script I would be really appreciative.
Try this: http://jsfiddle.net/xA5B7/
var MyDate = new Date();
var MyDateString;
MyDate.setDate(MyDate.getDate() + 20);
MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
+ ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
+ MyDate.getFullYear();
EDIT:
To explain, .slice(-2) gives us the last two characters of the string.
So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.
So if the MyDate.getMonth() returns 9, it will be:
("0" + "9") // Giving us "09"
so adding .slice(-2) on that gives us the last two characters which is:
("0" + "9").slice(-2)
"09"
But if MyDate.getMonth() returns 10, it will be:
("0" + "10") // Giving us "010"
so adding .slice(-2) gives us the last two characters, or:
("0" + "10").slice(-2)
"10"
The modern way
The new modern way to do this is to use toLocaleDateString, because it allows you not only to format a date with proper localization, but even to pass format options to achieve the desired result:
const date = new Date(2018, 2, 1)
const result = date.toLocaleDateString("en-GB", { // you can use undefined as first argument
year: "numeric",
month: "2-digit",
day: "2-digit",
})
console.log(result) // outputs “01/03/2018”
Or using a Temporal object (still in proposal, caniuse):
const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const result = date.toLocaleString("en-GB", { // you can use undefined as first argument
year: "numeric",
month: "2-digit",
day: "2-digit",
})
console.log(result) // outputs “01/03/2018”
When you use undefined as the first argument it will detect the browser language, instead. Alternatively, you can use 2-digit on the year option, too.
Performance
If you plan to format a lot of dates, you should consider using Intl.DateTimeFormat instead:
const formatter = new Intl.DateTimeFormat("en-GB", { // <- re-use me
year: "numeric",
month: "2-digit",
day: "2-digit",
})
const date = new Date(2018, 2, 1) // can also be a Temporal object
const result = formatter.format(date)
console.log(result) // outputs “01/03/2018”
The formatter is compatible with Date and Temporal objects.
Historical dates
Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so:
const date = new Date()
date.setFullYear(18, 2, 1) // the year is A.D. 18
This is not required for Temporal objects, but years below 1000 will not contain leading zeros in all cases, because the formatter (that is shared for the Date and Temporal API) does not support 4-digit formatting at all. In this case you have to do manual formatting (see below).
For the ISO 8601 format
If you want to get your date in the YYYY-MM-DD format (ISO 8601), the solution looks different:
const date = new Date(Date.UTC(2018, 2, 1))
const result = date.toISOString().split('T')[0]
console.log(result) // outputs “2018-03-01”
Your input date should be in the UTC format or toISOString() will fix that for you. This is done by using Date.UTC as shown above.
Historical dates for the ISO 8601 format
Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so to be used for the ISO 8601 format:
const date = new Date()
date.setUTCFullYear(18, 2, 1) // the year is A.D. 18
Note that the ISO format for Temporal objects with dates before the year 1000 or after the year 9999 will have a different formatting compared to the legacy Date API. It is recommend to fallback to custom formatting to enforce 4 digit years in all circumstances.
Custom 4-digit formatting on the year
Sadly, the formatter doesn't support leading zeros on the year. There is no 4-digit option. This will remain for Temporal objects as well, because they do share the same formatter.
Fortunately, the ISO format of the Date API will always display at least 4 digits on the year, although Temporal objects do not. So at least for the Date API you can format historical dates before the year 1000 with leading zeros by falling back to a manual formatting approach using part of the ISO 8601 format method:
const date = new Date()
date.setUTCFullYear(18, 2, 1)
const ymd = date.toISOString().split('T')[0].split('-')
const result = `${ymd[2]}/${ymd[1]}/${ymd[0]}`
console.log(result) // outputs “01/03/0018”
For a Temporal object a different route is necessary, since the ISOYearString will be formatted differently for dates before the year 1000 and after the year 9999 as mentioned before:
const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const zeroPad = (n, digits) => n.toString().padStart(digits, '0');
const result = `${zeroPad(date.day, 2)}/${zeroPad(date.month, 2)}/${zeroPad(date.year, 4)}`;
console.log(result) // outputs “01/03/0018”
Miscellaneous
For the Date and Temporal API there is also toLocaleTimeString, that allows you to localize and format the time of a date.
Here is an example from the Date object docs on the Mozilla Developer Network using a custom "pad" function, without having to extend Javascript's Number prototype. The handy function they give as an example is
function pad(n){return n<10 ? '0'+n : n}
And below is it being used in context.
/* use a function for the exact format desired... */
function ISODateString(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z
For you people from the future (ECMAScript 2017 and beyond)
Solution
"use strict"
const today = new Date()
const year = today.getFullYear()
const month = `${today.getMonth() + 1}`.padStart(2, "0")
const day = `${today.getDate()}`.padStart(2, "0")
const stringDate = [day, month, year].join("/") // 13/12/2017
Explaination
the String.prototype.padStart(targetLength[, padString]) adds as many as possible padString in the String.prototype target so that the new length of the target is targetLength.
Example
"use strict"
let month = "9"
month = month.padStart(2, "0") // "09"
let byte = "00000100"
byte = byte.padStart(8, "0") // "00000100"
You can define a "str_pad" function (as in php):
function str_pad(n) {
return String("00" + n).slice(-2);
}
I found the shorterst way to do this:
MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');
will add leading zeros to all lonely, single digits
Number.prototype.padZero= function(len){
var s= String(this), c= '0';
len= len || 2;
while(s.length < len) s= c + s;
return s;
}
//in use:
(function(){
var myDate= new Date(), myDateString;
myDate.setDate(myDate.getDate()+10);
myDateString= [myDate.getDate().padZero(),
(myDate.getMonth()+1).padZero(),
myDate.getFullYear()].join('/');
alert(myDateString);
})()
/* value: (String)
09/09/2010
*/
Nowadays you can also utilize String.prototype.padStart to reach the goal in quick and easy way
String(new Date().getMonth() + 1).padStart(2, '0')
The availability can be assessed at caniuse
var date = new Date()
var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')
console.log('%s/%s/%s', month, day, year)
Check
var date = new Date('7/4/2021')
var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')
/**
* Expected output: 07/04/2021
*/
console.log('%s/%s/%s', month, day, year)
Polyfill for old browsers
String.prototype.padStart || Object.defineProperty(String.prototype, 'padStart', {
configurable : true,
writable : true,
value : function (targetLength, padString) {
'use strict'
/**
* String.prototype.padStart polyfill
* https://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date
*/
targetLength = targetLength | 0
padString = arguments.length > 1 ? String(padString) : ' '
if (this.length < targetLength && padString.length) {
targetLength = targetLength - this.length
while (padString.length < targetLength) {
padString += padString
}
return padString.slice(0, targetLength) + this
} else {
return this
}
}
})
var MyDate = new Date();
var MyDateString = '';
MyDate.setDate(MyDate.getDate());
var tempoMonth = (MyDate.getMonth()+1);
var tempoDate = (MyDate.getDate());
if (tempoMonth < 10) tempoMonth = '0' + tempoMonth;
if (tempoDate < 10) tempoDate = '0' + tempoDate;
MyDateString = tempoDate + '/' + tempoMonth + '/' + MyDate.getFullYear();
There is another approach to solve this problem, using slice in JavaScript.
var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);
the datestring return date with format as you expect: 2019-09-01
another approach is using dateformat library: https://github.com/felixge/node-dateformat
You could use ternary operator to format the date like an "if" statement.
For example:
var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();
So
(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())
would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.
Edit:
Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.
function formatDate(jsDate){
// add leading zeroes to jsDate when days or months are < 10..
// i.e.
// formatDate(new Date("1/3/2013"));
// returns
// "01/03/2103"
////////////////////
return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" +
((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" +
jsDate.getFullYear();
}
You can provide options as a parameter to format date. First parameter is for locale which you might not need and second is for options.
For more info visit
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));
I wrapped the correct answer of this question in a function that can add multiple leading zero's but defaults to adding 1 zero.
function zeroFill(nr, depth){
depth = (depth === undefined)? 1 : depth;
var zero = "0";
for (var i = 0; i < depth; ++i) {
zero += "0";
}
return (zero + nr).slice(-(depth + 1));
}
for working with numbers only and not more than 2 digits, this is also an approach:
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
Another option, using a built-in function to do the padding (but resulting in quite long code!):
myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
+ '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
+ '/' + myDate.getFullYear();
// '12/06/2017'
And another, manipulating strings with regular expressions:
var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');
// '2017/06/12'
But be aware that one will show the year at the start and the day at the end.
Adding on to #modiX answer, this is what works...DO NOT LEAVE THAT as empty
today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})
Here is very simple example how you can handle this situation.
var mydate = new Date();
var month = (mydate.getMonth().toString().length < 2 ? "0"+mydate.getMonth().toString() :mydate.getMonth());
var date = (mydate.getDate().toString().length < 2 ? "0"+mydate.getDate().toString() :mydate.getDate());
var year = mydate.getFullYear();
console.log("Format Y-m-d : ",year+"-"+month+"-" + date);
console.log("Format Y/m/d : ",year+"/"+month+"/" + date);
I think this solution is easier and can be easily remembered:
var MyDate = new Date();
var day = MyDate.getDate() + 10; // 10 days in advance
var month = MyDate.getMonth() + 1; // since months start from 0 we should add 1 to it
var year = MyDate.getFullYear();
day = checkDate(day);
month = checkDate(month);
function checkDate(i){
if(i < 10){
i = '0' + i;
}
return i;
}
console.log(`${month}/${day}/${year}`);
What I would do, is create my own custom Date helper that looks like this :
var DateHelper = {
addDays : function(aDate, numberOfDays) {
aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
return aDate; // Return the date
},
format : function format(date) {
return [
("0" + date.getDate()).slice(-2), // Get day and pad it with zeroes
("0" + (date.getMonth()+1)).slice(-2), // Get month and pad it with zeroes
date.getFullYear() // Get full year
].join('/'); // Glue the pieces together
}
}
// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
(see also this Fiddle)
As #John Henckel suggests, starting using the toISOString() method makes things easier
const dateString = new Date().toISOString().split('-');
const year = dateString[0];
const month = dateString[1];
const day = dateString[2].split('T')[0];
console.log(`${year}-${month}-${day}`);
try this for a basic function, no libraries required
Date.prototype.CustomformatDate = function() {
var tmp = new Date(this.valueOf());
var mm = tmp.getMonth() + 1;
if (mm < 10) mm = "0" + mm;
var dd = tmp.getDate();
if (dd < 10) dd = "0" + dd;
return mm + "/" + dd + "/" + tmp.getFullYear();
};
You could simply use :
const d = new Date();
const day = `0${d.getDate()}`.slice(-2);
So a function could be created like :
AddZero(val){
// adding 0 if the value is a single digit
return `0${val}`.slice(-2);
}
Your new code :
var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
toISOString can get leading 0
const currentdate = new Date();
const date = new Date(Date.UTC(currentdate.getFullYear(), (currentdate.getMonth()),currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), currentdate.getSeconds()));
//you can pass YY, MM, DD //op: 2018-03-01
//i have passed YY, MM, DD, HH, Min, Sec // op : 2021-06-09T12:14:27.000Z
console.log(date.toISOString());
output will be similar to this : 2021-06-09T12:14:27.000Z
const month = date.toLocaleDateString('en-US', { month: '2-digit' });
const day = date.toLocaleDateString('en-US', { day: '2-digit' });
const year = date.getFullYear();
const dateString = `${month}-${day}-${year}`;
The following aims to extract configuration, hook into Date.protoype and apply configuration.
I've used an Array to store time chunks and when I push() this as a Date object, it returns me the length to iterate. When I'm done, I can use join on the return value.
This seems to work pretty fast: 0.016ms
// Date protoype
Date.prototype.formatTime = function (options) {
var i = 0,
time = [],
len = time.push(this.getHours(), this.getMinutes(), this.getSeconds());
for (; i < len; i += 1) {
var tick = time[i];
time[i] = tick < 10 ? options.pad + tick : tick;
}
return time.join(options.separator);
};
// Setup output
var cfg = {
fieldClock: "#fieldClock",
options: {
pad: "0",
separator: ":",
tick: 1000
}
};
// Define functionality
function startTime() {
var clock = $(cfg.fieldClock),
now = new Date().formatTime(cfg.options);
clock.val(now);
setTimeout(startTime, cfg.options.tick);
}
// Run once
startTime();
demo: http://jsfiddle.net/tive/U4MZ3/
Add some padding to allow a leading zero - where needed - and concatenate using your delimiter of choice as string.
Number.prototype.padLeft = function(base,chr){
var len = (String(base || 10).length - String(this).length)+1;
return len > 0? new Array(len).join(chr || '0')+this : this;
}
var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');
let date = new Date();
let dd = date.getDate();//day of month
let mm = date.getMonth();// month
let yyyy = date.getFullYear();//day of week
if (dd < 10) {//if less then 10 add a leading zero
dd = "0" + dd;
}
if (mm < 10) {
mm = "0" + mm;//if less then 10 add a leading zero
}
function pad(value) {
return value.tostring().padstart(2, 0);
}
let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);
You can use String.slice() which extracts a section of a string and returns it as a new string, without modifying the original string:
const currentDate = new Date().toISOString().slice(0, 10) // 2020-04-16
Or you can also use a lib such as Moment.js to format the date:
const moment = require("moment")
const currentDate = moment().format("YYYY-MM-DD") // 2020-04-16
A simple dateformat library saved my life (GitHub):
Node.js: var dateFormat = require("dateformat");
ES6: import dateFormat from "dateformat";
const now = new Date(); // consider 3rd of December 1993
const full = dateFormat(today, "yyyy-mm-dd"); // 1993-12-03
const day = dateFormat(today, "dd"); // 03
const month = dateFormat(today, "mm"); // 12
const year = dateFormat(today, "yyyy"); // 1993
It's worth to mention it supports a wide range of mask options.