Javascript get start of the month - javascript

How to get the start of the month in date format e.g. 01-05-2017?
I have already seen
Get first and last date of current month with javascript or jquery

If I understand correctly toLocaleString() might do what you want.
For example:
lastDay.toLocaleString('en-GB', {day: 'numeric', month: '2-digit', year: 'numeric'});
For more info (MDN)
Replace locale with any that suits your desired formatting.

After getting the date we need to convert it to desired string format.
01 is the day and may be a constant since every beginning of the month starts from 1.
getMonth returns number of the month starting from 0 so we need a little function to format it.
var date = new Date();
var startDate = new Date(date.getFullYear(), date.getMonth(), 1);
var startDateString = '01-' + fotmatMonth(startDate.getMonth()) + '-' + startDate.getFullYear();
console.log(startDateString);
function fotmatMonth(month) {
month++;
return month < 10 ? '0' + month : month;
}

var date = new Date();
console.log(getStartOfMonthDateAsString(date));
function getStartOfMonthDateAsString() {
function zerosPad(number, numOfZeros) {
var zero = numOfZeros - number.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + number;
}
var day = zerosPad(1, 2);
var month = zerosPad((date.getMonth() + 1), 2);
var year = date.getFullYear();
return day + '-' + month + '-' + year;
}

Related

Add trailing zero in time format in jquery [duplicate]

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.

Date code not working in JS

I bet this is something really silly but I am tired and looking for a quick escape so please indulge me. Objective is to be able to add arbitrary days to a date constructed from a string like 2015-01-01.
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date) {
var year = date.getFullYear();
var month = date.getMonth().toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month + '-' + day;
}
And then :
I get the output which is wrong because I am adding 90 days..
Two dates: 2015-01-01 2015-02-31
The problem lies in this line:
var month = date.getMonth().toString();
The function Date.getMonth() returns “the month (0-11) in the specified date according to local time”. January is 0, December is 11, so you need to add 1 to the output:
var month = "" + (date.getMonth()+1);
var month = date.getMonth().toString(); prints the no of months starting from no 0 so the month number is reduced by 1 for eg. the value of january from date.getMonth(); would be 0 and so on till 11.
here's the correct version for your code
firstDate = '2015-01-01';
var t1_date = new Date(firstDate);
console.log("before conversion");
console.log(t1_date);//before conversion
t1_date.setTime( t1_date.getTime() + 90 * 86400000 );
console.log("after conversion");
console.log(t1_date);//after conversion
lastDate = getFormattedDate(t1_date);
console.log("Two dates: ", firstDate, lastDate);
function getFormattedDate(date)
{
var year = date.getFullYear();
var month = date.getMonth();
var month1=(month+1).toString();
month1 = month1.length > 1 ? month1 : '0' + month1;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year + '-' + month1 + '-' + day;
}
Never parse strings with the Date constructor, always manually parse them. An ISO date without a timezone should be treated as local*, however ES5 said to treat it as UTC, then ECMAScript 2015 inferred to treat them as local (hooray for consistency) but then the implementors decided to treat them as UTC again, so browsers might do either (or NaN).
So the sensible thing is to manually parse them as local.
Outputting as a local ISO date is also fairly simple.
* Where local means per system settings.
function parseISODate(s) {
var b = s.split(/\D/);
var d = new Date(b[0], --b[1], b[2]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
document.write(parseISODate('2015-01-01') + '<br>');
function toISODate(date) {
function z(n){return ('0'+n).slice(-2)}
return date.getFullYear() + '-' + z(date.getMonth() + 1) + '-' + z(date.getDate());
}
document.write(toISODate(parseISODate('2015-01-01')));
To add 90 days, it is simpler to just add 90 days to the date:
var d = new Date(2015,0,1); // 1 January 2015
d.setDate(d.getDate() + 90); // add 90 days
document.write(d.toLocaleString()); // 1 April 2015

A twofold javascript function to convert a long date and return today's date in mm-dd-yyyy format

I need your help,
I can't seem to find any other help on this on the internet, because it seems its either one way ot the other. What I would like to be able to do is to create a combined, two-fold javascript function that would convert a long date string into the mm-dd-yyyy format, and when the same function is called again with no string specified to convert, to just return todays date in mm-dd-yyyy format.
Example:
getDate(Fri May 22 2015 13:32:25 GMT-0400)
would return: 05-22-2015
getDate()
would return today's date of 05-23-2015
Hi this should do the trick
FORMAT: mm-dd-yyyy
function addZeroIfRequired(dayOrMonth) {
return dayOrMonth > 9 ? dayOrMonth : "0"+dayOrMonth;
}
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return addZeroIfRequired((date.getUTCMonth()+1)) + "-" +
addZeroIfRequired(date.getDate())+ "-" +
date.getUTCFullYear();
}
console.log(getDate()); // 05-23-2015
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400")); 05-22-2015
NOTE: the +1 after the getUTCMonth().
JSFiddle. Open the console to see the result. https://jsfiddle.net/wt79yLo0/2/
ISO FORMAT: yyyy-mm-dd
Just in case someone is interested in the opposite format, the code would be much nicer and neater:
function getDate(dateString) {
var date = dateString ? new Date(dateString) : new Date();
return date.toISOString().substring(0, 10);
}
console.log(getDate());
console.log(getDate("Fri May 22 2015 13:32:25 GMT-0400"));
https://jsfiddle.net/wt79yLo0/
First I would recommend a very powerful library for JS called Moment.js which solves all this kind of problems.
But if you only want a snippet, here is my proposal:
function twoDigits(num) {
return ("0" + num).substr(-2);
}
function getFormattedDateDMY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [day,month,year].join(separator);
}
function getFormattedDateMDY(date, separator) {
var day = twoDigits(date.getDate());
var month = twoDigits(date.getMonth());
var year = date.getFullYear();
return [month,day,year].join(separator);
}
console.log(getFormattedDateDMY(new Date(), "-")); //23-04-2015
console.log(getFormattedDateMDY(new Date(), "-")); //04-23-2015
With getDate(), getMonth() and getFullYear(). You have to set a "0" before the months and days which are < 10. GetMonth() starts with 0, therefore (getMonth() + 1).
function getFormattedDate() {
var date = new Date();
var day = date.getDate() > 9 ? date.getDate() : "0" + date.getDate();
var month = (date.getMonth() + 1) > 9 ? (date.getMonth() + 1) : "0" + (date.getMonth() + 1);
var year = date.getFullYear();
var formattedDate = day + "-" + month + "-" + year;
return formattedDate;
}
console.log(getFormattedDate());
Demo

How do I get Month and Date of JavaScript in 2 digit format?

When we call getMonth() and getDate() on date object, we will get the single digit number.
For example :
For january, it displays 1, but I need to display it as 01. How to do that?
("0" + this.getDate()).slice(-2)
for the date, and similar:
("0" + (this.getMonth() + 1)).slice(-2)
for the month.
If you want a format like "YYYY-MM-DDTHH:mm:ss", then this might be quicker:
var date = new Date().toISOString().substr(0, 19);
// toISOString() will give you YYYY-MM-DDTHH:mm:ss.sssZ
Or the commonly used MySQL datetime format "YYYY-MM-DD HH:mm:ss":
var date2 = new Date().toISOString().substr(0, 19).replace('T', ' ');
Why not use padStart ?
padStart(targetLength, padString) where
targetLength is 2
padString is 0
// Source: https://stackoverflow.com/a/50769505/2965993
var dt = new Date();
year = dt.getFullYear();
month = (dt.getMonth() + 1).toString().padStart(2, "0");
day = dt.getDate().toString().padStart(2, "0");
console.log(year + '/' + month + '/' + day);
This will always return 2 digit numbers even if the month or day is less than 10.
Notes:
This will only work with Internet Explorer if the js code is transpiled using babel.
getFullYear() returns the 4 digit year and doesn't require padStart.
getMonth() returns the month from 0 to 11.
1 is added to the month before padding to keep it 1 to 12.
getDate() returns the day from 1 to 31.
The 7th day will return 07 and so we do not need to add 1 before padding the string.
Example for month:
function getMonth(date) {
var month = date.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
You can also extend Date object with such function:
Date.prototype.getMonthFormatted = function() {
var month = this.getMonth() + 1;
return month < 10 ? '0' + month : '' + month; // ('' + month) for string result
}
The best way to do this is to create your own simple formatter (as below):
getDate() returns the day of the month (from 1-31)
getMonth() returns the month (from 0-11) < zero-based, 0=January, 11=December
getFullYear() returns the year (four digits) < don't use getYear()
function formatDateToString(date){
// 01, 02, 03, ... 29, 30, 31
var dd = (date.getDate() < 10 ? '0' : '') + date.getDate();
// 01, 02, 03, ... 10, 11, 12
var MM = ((date.getMonth() + 1) < 10 ? '0' : '') + (date.getMonth() + 1);
// 1970, 1971, ... 2015, 2016, ...
var yyyy = date.getFullYear();
// create the format you want
return (dd + "-" + MM + "-" + yyyy);
}
I would do this:
var date = new Date(2000, 0, 9);
var str = new Intl.DateTimeFormat('en-US', {
month: '2-digit',
day: '2-digit',
year: 'numeric'
}).format(date);
console.log(str); // prints "01/09/2000"
The following is used to convert db2 date format
i.e YYYY-MM-DD using ternary operator
var currentDate = new Date();
var twoDigitMonth=((currentDate.getMonth()+1)>=10)? (currentDate.getMonth()+1) : '0' + (currentDate.getMonth()+1);
var twoDigitDate=((currentDate.getDate())>=10)? (currentDate.getDate()) : '0' + (currentDate.getDate());
var createdDateTo = currentDate.getFullYear() + "-" + twoDigitMonth + "-" + twoDigitDate;
alert(createdDateTo);
Just another example, almost one liner.
var date = new Date();
console.log( (date.getMonth() < 9 ? '0': '') + (date.getMonth()+1) );
function monthFormated(date) {
//If date is not passed, get current date
if(!date)
date = new Date();
month = date.getMonth();
// if month 2 digits (9+1 = 10) don't add 0 in front
return month < 9 ? "0" + (month+1) : month+1;
}
If it might spare some time I was looking to get:
YYYYMMDD
for today, and got along with:
const dateDocumentID = new Date()
.toISOString()
.substr(0, 10)
.replace(/-/g, '');
function monthFormated() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
This was my solution:
function leadingZero(value) {
if (value < 10) {
return "0" + value.toString();
}
return value.toString();
}
var targetDate = new Date();
targetDate.setDate(targetDate.getDate());
var dd = targetDate.getDate();
var mm = targetDate.getMonth() + 1;
var yyyy = targetDate.getFullYear();
var dateCurrent = leadingZero(mm) + "/" + leadingZero(dd) + "/" + yyyy;
Using Moment.js it can be done like that:
moment(new Date(2017, 1, 1)).format('DD') // day
moment(new Date(2017, 1, 1)).format('MM') // month
const today = new Date().toISOString()
const fullDate = today.split('T')[0];
console.log(fullDate) //prints YYYY-MM-DD
Not an answer but here is how I get the date format I require in a variable
function setDateZero(date){
return date < 10 ? '0' + date : date;
}
var curr_date = ev.date.getDate();
var curr_month = ev.date.getMonth() + 1;
var curr_year = ev.date.getFullYear();
var thisDate = curr_year+"-"+setDateZero(curr_month)+"-"+setDateZero(curr_date);
Hope this helps!
Ternary Operator Solution
A simple ternary operator can add a "0" before the number if the month or day is less than 10 (assuming you need this information for use in a string).
let month = (date.getMonth() < 10) ? "0" + date.getMonth().toString() : date.getMonth();
let day = (date.getDate() < 10) ? "0" + date.getDate().toString() : date.getDate();
The more modern approach perhaps, using "padStart"
const now = new Date();
const day = `${now.getDate()}`.padStart(2, '0');
const month = `${now.getMonth()}`.padStart(2, '0');
const year = now.getFullYear();
then you can build as a template string if you wish:
`${day}/${month}/${year}`
Tip from MDN :
function date_locale(thisDate, locale) {
if (locale == undefined)
locale = 'fr-FR';
// set your default country above (yes, I'm french !)
// then the default format is "dd/mm/YYY"
if (thisDate == undefined) {
var d = new Date();
} else {
var d = new Date(thisDate);
}
return d.toLocaleDateString(locale);
}
var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);
http://jsfiddle.net/v4qcf5x6/
new Date().getMonth() method returns the month as a number (0-11)
You can get easily correct month number with this function.
function monthFormatted() {
var date = new Date(),
month = date.getMonth();
return month+1 < 10 ? ("0" + month) : month;
}
I would suggest you use a different library called Moment https://momentjs.com/
This way you are able to format the date directly without having to do extra work
const date = moment().format('YYYY-MM-DD')
// date: '2020-01-04'
Make sure you import moment as well to be able to use it.
yarn add moment
# to add the dependency
import moment from 'moment'
// import this at the top of the file you want to use it in
Hope this helps :D
How it easy?
new Date().toLocaleString("en-US", { day: "2-digit" })
Another options are available such:
weekday
year
month
More info here.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString#using_options
function GetDateAndTime(dt) {
var arr = new Array(dt.getDate(), dt.getMonth(), dt.getFullYear(),dt.getHours(),dt.getMinutes(),dt.getSeconds());
for(var i=0;i<arr.length;i++) {
if(arr[i].toString().length == 1) arr[i] = "0" + arr[i];
}
return arr[0] + "." + arr[1] + "." + arr[2] + " " + arr[3] + ":" + arr[4] + ":" + arr[5];
}
And another version here https://jsfiddle.net/ivos/zcLxo8oy/1/, hope to be useful.
var dt = new Date(2016,5,1); // just for the test
var separator = '.';
var strDate = (dt.getFullYear() + separator + (dt.getMonth() + 1) + separator + dt.getDate());
// end of setup
strDate = strDate.replace(/(\b\d{1}\b)/g, "0$1")
The answers here were helpful, however I need more than that: not only month, date, month, hours & seconds, for a default name.
Interestingly, though prepend of "0" was needed for all above, " + 1" was needed only for month, not others.
As example:
("0" + (d.getMonth() + 1)).slice(-2) // Note: +1 is needed
("0" + (d.getHours())).slice(-2) // Note: +1 is not needed
My solution:
function addLeadingChars(string, nrOfChars, leadingChar) {
string = string + '';
return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}
Usage:
var
date = new Date(),
month = addLeadingChars(date.getMonth() + 1),
day = addLeadingChars(date.getDate());
jsfiddle: http://jsfiddle.net/8xy4Q/1/
var net = require('net')
function zeroFill(i) {
return (i < 10 ? '0' : '') + i
}
function now () {
var d = new Date()
return d.getFullYear() + '-'
+ zeroFill(d.getMonth() + 1) + '-'
+ zeroFill(d.getDate()) + ' '
+ zeroFill(d.getHours()) + ':'
+ zeroFill(d.getMinutes())
}
var server = net.createServer(function (socket) {
socket.end(now() + '\n')
})
server.listen(Number(process.argv[2]))
if u want getDate() function to return the date as 01 instead of 1, here is the code for it....
Lets assume Today's date is 01-11-2018
var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();
console.log(today); //Output: 2018-11-1
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today); //Output: 2018-11-01
I wanted to do something like this and this is what i did
p.s. i know there are right answer(s) on top, but just wanted to add something of my own here
const todayIs = async () =>{
const now = new Date();
var today = now.getFullYear()+'-';
if(now.getMonth() < 10)
today += '0'+now.getMonth()+'-';
else
today += now.getMonth()+'-';
if(now.getDay() < 10)
today += '0'+now.getDay();
else
today += now.getDay();
return today;
}
If you'll check smaller than 10, you haven't to create a new function for that. Just assign a variable into brackets and return it with ternary operator.
(m = new Date().getMonth() + 1) < 10 ? `0${m}` : `${m}`
currentDate(){
var today = new Date();
var dateTime = today.getFullYear()+'-'+
((today.getMonth()+1)<10?("0"+(today.getMonth()+1)):(today.getMonth()+1))+'-'+
(today.getDate()<10?("0"+today.getDate()):today.getDate())+'T'+
(today.getHours()<10?("0"+today.getHours()):today.getHours())+ ":" +
(today.getMinutes()<10?("0"+today.getMinutes()):today.getMinutes())+ ":" +
(today.getSeconds()<10?("0"+today.getSeconds()):today.getSeconds());
return dateTime;
},

Javascript add leading zeroes to date

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.

Categories