Generating series of dates between two given date with simplified method [duplicate] - javascript

This question already has answers here:
Javascript - get array of dates between 2 dates
(31 answers)
Closed 3 years ago.
I need to generate the series of all dates between two given dates. How ever I am not able to get desire output.
I tried using the below code. I gt an empty array.
function getDates(startDate, endDate) {
var dates = [];
var currentDate = new Date(startDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate = currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
};
When I execute console.log(getDates("2019-10-10","2019-11-20")), I get the result as empty array. I didn't get the series of dates as a result.

As mentioned by #RobG, parsing date can yield different results hence consider using the following:
function parseDate(input) {
var parts = input.split('-');
return new Date(parts[0], parts[1] - 1, parts[2]);
}
function getDates(startDate, endDate) {
var dates = [];
var currentDate = parseDate(startDate);
endDate = parseDate(endDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
}
console.log(getDates("2019-10-10", "2019-11-20"));
Original Answer:
You could change endDate into Date type and not set currentDate as setDate is doing it for you:
function getDates(startDate, endDate) {
var dates = [];
var currentDate = new Date(startDate);
endDate = new Date(endDate);
while (currentDate <= endDate) {
var final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate.setDate(currentDate.getDate() + 1);
}
return dates;
}
console.log(getDates("2019-10-10", "2019-11-20"));

You have to call new Date() on line 8.
function getDates(startDate, endDate) {
const dates = [];
let currentDate = new Date(startDate);
while (currentDate <= new Date(endDate)) {
const final = currentDate.getFullYear() + '-' + (((currentDate.getMonth() + 1) < 10) ? '0' : '') + (currentDate.getMonth() + 1) + '-' + ((currentDate.getDate() < 10) ? '0' : '') + currentDate.getDate();
dates.push(final);
currentDate = new Date(currentDate.setMonth(currentDate.getMonth()+1))
}
return dates;
};
const dates = getDates("2019-01-01", "2019-10-01");
console.log(dates);

As others have said, you're comparing a string and a Date, so things go awry.
ISO 8601 format dates can be compared as strings without being parsed to Dates. Timestamps in the format YYY-MM-DD are parsed as UTC, so you need to be careful with manipulating them. In the OP, the strings are parsed as UTC but local methods are used to format the timestamps, so they may be out by 1 day for users west of Greenwich.
One option is to use UTC methods for incrementing the date and to create strings for comparison, e.g.
// startDate, endDate in format YYYY-MM-DD
function getDates(startDate, endDate) {
let toISODate = date => date.toISOString().substr(0,10);
var dates = [];
var currentDate = new Date(startDate);
while (startDate <= endDate) {
dates.push(startDate);
currentDate.setUTCDate(currentDate.getUTCDate() + 1);
startDate = toISODate(currentDate);
}
return dates;
};
console.log(getDates('2019-09-01', '2019-10-01'));

Use a library like moment.js for date manipulation. These functions are readily available in these.
window['moment-range'].extendMoment(moment);
const start = new Date("11/30/2018"), end = new Date("09/30/2019")
const range = moment.range(moment(start), moment(end));
console.log(Array.from(range.by('day')))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-range/4.0.1/moment-range.js"></script>
And this question has lot of other methods as answers - from which I copied the above solution.

Related

Rearrange date fromat

Is there a better way to write this code? I'm taking a "date" parameter (which is a string in this case) thats formatted in one of two ways mm/dd/yy' or m/d/yy and I need to reformat it to look like this yyyymmdd
functionName = function(date){
var month = "", day = "", year = "";
if(!date.length) return;
else {
date.slice(0, 2) < 10 ? month = '0' + date.slice(0, 2) : month = date.slice(0, 2);
date.slice(3, 5) < 10 ? day = '0' + date.slice(3, 5) : day = date.slice(3, 5);
year = "20" + date.slice(6, 8);
}
return year + month + day;
}
Also how should I check to see if the date was in the 1900's and format it accordingly?
There is no way to make a full year from a two digit year, it's missing information.
However you could simplify your function using .split() and .padStart()
function FormatDate (date) {
if (date) {
date = date.split('/'); //date[0] = month, date[1] = day, date[2] = year
return date[2] + date[0].padStart(2, '0') + date[1].padStart(2, '0');
}
}
console.log(FormatDate('07/09/20')); //outputs 200709

Set validation to check two dates with javascript

I am trying to find the difference between two dates,when the user wants to change arrival date, remember the number of days between arrival/departure before the change , after changing arrival date , automatically set departure date to be x days after arrival date ,
So, if i have 01JUN17 - 05JUN17 (4days) and the user changes the arrival date to 04JUN17 then set departure to 08JUN17 (+4 days)
function changedDate() {
var startDate = $("#Arrival").val().split("-");
var endDate = $("#Departure").val().split("-");
var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
var timeDiff = Math.abs(departureDate.getDate() - arrivalDate.getDate());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
if (arrivalDate >= departureDate) {
var arrDate = arrivalDate;
arrDate.setDate(arrDate.getDate() + 1);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
$("#Departure").val(day + '-' + month + '-' + year);
}
if (timeDiff > 1) {
var arrDate = arrivalDate;
var depDate = departureDate;
arrDate.setDate(arrDate.getDate());
depDate.setDate(depDate.getDate() + diffDays);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
var monthd = depDate.getMonth() + 1;
if (monthd < 10)
monthd = '0' + month;
var dayd = depDate.getDate();
if (dayd < 10)
dayd = '0' + day;
var yeard = depDate.getFullYear();
$("#Arrival").val(day + '-' + month + '-' + year);
$("#Departure").val(dayd + '-' + monthd + '-' + yeard);
}
if(arrivalDate < departureDate) {
var arrDate = arrivalDate;
arrDate.setDate(arrDate.getDate() + 1);
var month = arrDate.getMonth() + 1;
if (month < 10)
month = '0' + month;
var day = arrDate.getDate();
if (day < 10)
day = '0' + day;
var year = arrDate.getFullYear();
$("#Departure").val(day + '-' + month + '-' + year);
}
}
this condition not related with the validation that i want this is to
set departureDate +1 after arrival date on change
if (arrivalDate >= departureDate)
this condition not related with the validation that i want this is to
set departureDate +1 after arrival date on change
if(arrivalDate < departureDate)
this condition i make it for this validation but didn't work
if (timeDiff > 1)
Instead of using the getDate() method to calculate the timeDiff, use getTime() and do a simple subtraction, followed by a millisecond-to-days refactoring.
Something like this:
var startDate = $("#Arrival").val().split("-");
var endDate = $("#Departure").val().split("-");
var arrivalDate = new Date(startDate[2], startDate[1] - 1, startDate[0]);
var departureDate = new Date(endDate[2], endDate[1] - 1, endDate[0]);
var timeDiff = Math.abs(departureDate.getTime() - arrivalDate.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
Additionally, while subtracting Date type values, the getTime() method becomes optional and a direct subtraction departureDate - arrivalDate can also be done.
If you're using datejs, creating a TimeSpan will help here.
var sync = function () {
var val1 = $("#Arrival").val();
var val2 = $("#Departure").val();
var startDate = Date.parseExact(val1, "ddMMMyy");
var endDate = Date.parseExact(val2, "ddMMMyy");
var diff = new TimeSpan(endDate - startDate);
var newEndDate = startDate.add(diff.days).days();
$("#Departure").val(newEndDate.toString("ddMMyyy"));
};
You could trigger this function to automatically fire by wiring up a change listener on the startDate input field. Just a thought.
Hope this helps.
To do this you need to remember either the arrival date before it was modified, or the number of days between arrival and departure dates. That way you can adjust the departure date by whatever amount the arrival date moved by.
You can store the "old" arrival date in lots of places, the defaultValue might be a good place. So when arrival date is updated, compare the new arrival date to the old one, set the old do the new one and adjust the departure date accordingly, e.g.
// Some helper functions
function parseDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && d.getMonth() == b[1]? d : new Date(NaN);
}
function formatDate(date) {
if (isNaN(date)) return date.toString();
function z(n){return (n<10?'0':'')+n}
return z(date.getDate()) + '-' +
z(date.getMonth()+1) + '-' +
date.getFullYear();
}
function arrivalChange() {
// Check value entered is valid, if so,
// make sure formatted correctly
var arrDate = parseDMY(this.value);
// Deal with invalid input
if (isNaN(arrDate)) {
this.value = "Invalid date";
this.focus();
return;
}
// Tidy formatting
this.value = formatDate(arrDate);
var daysDiff, depDate;
var depEl = this.form.departureDate;
// Get number of days shifted and move departure date accordingly
daysDiff = Math.round((arrDate - parseDMY(this.defaultValue)) / 8.64e7);
this.defaultValue = this.value;
depDate = parseDMY(this.form.departureDate.defaultValue);
depDate.setDate(depDate.getDate() + daysDiff);
this.form.departureDate.value = formatDate(depDate);
this.form.departureDate.defaultValue = formatDate(depDate);
}
function departureChange(){
// Check value entered is valid, if so,
// make sure formatted correctly
var depDate = parseDMY(this.value);
if (isNaN(depDate)) {
this.value = 'Invalid date';
this.focus();
} else {
this.value = formatDate(depDate);
this.defaultValue = formatDate(depDate);
}
}
// Set dates in inputs, attach listeners
window.onload = function() {
var form = document.forms[0];
var now = new Date();
form.arrivalDate.value = formatDate(now);
form.arrivalDate.defaultValue = form.arrivalDate.value;
now.setDate(now.getDate() + 1);
form.departureDate.value = formatDate(now);
form.departureDate.defaultValue = form.departureDate.value;
form.arrivalDate.addEventListener('change', arrivalChange, false);
form.departureDate.addEventListener('change', departureChange, false);
};
<form onsubmit="return false;">
Arrival date (dd-mm-yyy): <input name="arrivalDate"><br>
Departure date (dd-mm-yyy): <input name="departureDate"><br>
<input type="reset">
</form>
If the user enters an invalid date at any time, pressing reset should get back the previous values.

Javascript increment and decrement YYYY-MM-DD by 1 day

I got this from another stack question
incr_date(date_str){
let parts = date_str.split("-");
let dt = new Date(
parseInt(parts[0], 10), // year
parseInt(parts[1], 10) - 1, // month (starts with 0)
parseInt(parts[2], 10) // date
);
dt.setDate(dt.getDate() + 1);
parts[0] = "" + dt.getFullYear();
parts[1] = "" + (dt.getMonth() + 1);
if (parts[1].length < 2) {
parts[1] = "0" + parts[1];
}
parts[2] = "" + dt.getDate();
if (parts[2].length < 2) {
parts[2] = "0" + parts[2];
}
return parts.join("-");
}
It works but how can I convert this function to decrement the date instead of increment?
I'm doing this on a react native component so I dont want to import any javascript libraries like moment.js
function dateAdd(dte){
var date = new Date(dte);
date.setDate(date.getDate() + 1);
console.log("add one day= "+date)
}
function datesub(dte){
var date = new Date(dte);
date.setDate(date.getDate() - 1);
console.log("minus one day = "+ date)
}
dateAdd("01-01-2017")
datesub("01-01-2017")
I'd convert the string to Javascript understandable format, increment a day and convert it back to user understandable format. I'm using the flag(Boolean) to determine weather to Increment the date and vice versa.
var convertDate = function(dt, flag) {
var dateArr = dt.split('-');
var tempDate = new Date();
var mm = dateArr[1] - 1; //Javascript considers 0 as Jan
tempDate.setFullYear(dateArr[0]);
tempDate.setMonth(mm);
tempDate.setDate(dateArr[2]);
if (flag) {
tempDate.setDate(tempDate.getDate(dateArr[2]) + 1);//Add's one day
} else {
tempDate.setDate(tempDate.getDate(dateArr[2]) - 1);//Sub's one day
}
var userFriendlyMonth = (Number(tempDate.getMonth()) + 1); //user considers 1 as Jan
return tempDate.getFullYear() + '-' + userFriendlyMonth + '-' + tempDate.getDate();
}
document.getElementById("increment").innerHTML = convertDate('2018-11-30', true);
document.getElementById("decrement").innerHTML = convertDate('2018-11-30', false);
<div>Increment: <span id="increment"></span></div>
<div>Decrement: <span id="decrement"></span></div>

Javascript date - Leading 0 for days and months where applicable

Is there a clean way of adding a 0 in front of the day or month when the day or month is less than 10:
var myDate = new Date();
var prettyDate =(myDate.getFullYear() +'-'+ myDate.getMonth()) +'-'+ myDate.getDate();
This would output as:
2011-8-8
I would like it to be:
2011-08-08
The format you seem to want looks like ISO. So take advantage of toISOString():
var d = new Date();
var date = d.toISOString().slice(0,10); // "2014-05-12"
No, there is no nice way to do it. You have to resort to something like:
var myDate = new Date();
var year = myDate.getFullYear();
var month = myDate.getMonth() + 1;
if(month <= 9)
month = '0'+month;
var day= myDate.getDate();
if(day <= 9)
day = '0'+day;
var prettyDate = year +'-'+ month +'-'+ day;
var myDate = new Date();
var m = myDate.getMonth() + 1;
var d = myDate.getDate();
m = m > 9 ? m : "0"+m;
d = d > 9 ? d : "0"+d;
var prettyDate =(myDate.getFullYear() +'-'+ m) +'-'+ d;
...and a sample: http://jsfiddle.net/gFkaP/
You can try like this
For day:
("0" + new Date().getDate()).slice(-2)
For month:
("0" + (new Date().getMonth() + 1)).slice(-2)
For year:
new Date().getFullYear();
You will have to manually check if it needs a leading zero and add it if necessary...
var m = myDate.getMonth();
var d = myDate.getDate();
if (m < 10) {
m = '0' + m
}
if (d < 10) {
d = '0' + d
}
var prettyDate = myDate.getFullYear() +'-'+ m +'-'+ d;
Yes, get String.js by Rumata and then use:
'%04d-%02d-%02d'.sprintf(myDate.getFullYear(),
myDate.getMonth() + 1,
myDate.getDate());
NB: don't forget the + 1 on the month field. The Date object's month field starts from zero, not one!
If you don't want to use an extra library, a trivial inline function will do the job of adding the leading zeroes:
function date2str(d) {
function fix2(n) {
return (n < 10) ? '0' + n : n;
}
return d.getFullYear() + '-' +
fix2(d.getMonth() + 1) + '-' +
fix2(d.getDate());
}
or even add it to the Date prototype:
Date.prototype.ISO8601date = function() {
function fix2(n) {
return (n < 10) ? '0' + n : n;
}
return this.getFullYear() + '-' +
fix2(this.getMonth() + 1) + '-' +
fix2(this.getDate());
}
usage (see http://jsfiddle.net/alnitak/M5S5u/):
var d = new Date();
var s = d.ISO8601date();
For Month,
var month = ("0" + (myDate.getMonth() + 1)).slice(-2);
For Day,
var day = ("0" + (myDate.getDate() + 1)).slice(-2);
Unfortunately there's no built-in date-format in javascript. Either use a existing library (example http://blog.stevenlevithan.com/archives/date-time-format) or build your own method for adding a leading zero.
var addLeadingZeroIfNeeded = function addLeadingZeroIfNeeded(dateNumber) {
if (String(dateNumber).length === 1) {
return '0' + String(dateNumber);
}
return String(dateNumber);
},
myDate = new Date(),
prettyDate;
prettyDate = myDate.getFullYear() + '-' + addLeadingZeroIfNeeded(myDate.getMonth()) + '-' + addLeadingZeroIfNeeded(myDate.getDate());
EDIT
As Alnitak said, keep in mind that month i JavaScript starts on 0 not 1.
The easiest way to do this is to prepend a zero and then use .slice(-2).
With this function you always return the last 2 characters of a string.
var month = 8;
var monthWithLeadingZeros = ('0' + month).slice(-2);
Checkout this example:
http://codepen.io/Shven/pen/vLgQMQ?editors=101

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;
},

Categories