I want to change this date to be formatted to DD-MM-YY
new Date(new Date().setDate(new Date().getDate() + 7)))
Current result: Thu Sep 15 2022 02:16:38 GMT+0200 (Central European Summer Time)
Wanted result: 15-09-22
I suggest solving the problem step by step.
Check the Date object documentation. There are methods that return the day, month, and year.
Add leading "0" when you need it. For instance, like this: ${value < 10 ? '0' : ''}${value}.
Concatenate the strings:
`${dayString}-${monthString}-${date.getFullYear()}`
let date = new Date()
date.setDate(date.getDate() + 7);
const day = date.getDate();
const month = date.getMonth();
const dayString = `${day < 10 ? '0' : ''}${day}`;
const monthString = `${month < 10 ? '0' : ''}${month}`;
const formatted = `${dayString}-${monthString}-${date.getFullYear()}`;
const event = new Date(new Date().setDate(new Date().getDate() + 7));
var day = event.getDate();
var month = event.getMonth();
var year = event.getFullYear();
var date = day + '-' + month + '-' + year;
date.toString();
I did find a fix for my issues no more comments are necessary
Let's say we have this datetime:
var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
Exporting it as a string (console.log(d)) gives inconsistent results among browsers:
Sat Jul 21 2018 14:00:00 GMT+0200 (Paris, Madrid (heure d’été)) with Chrome
Sat Jul 21 14:00:00 UTC+0200 2018 with Internet Explorer, etc.
so we can't send datetime to a server with an unconsistent format.
The natural idea then would be to ask for an ISO8601 datetime, and use d.toISOString(); but it gives the UTC datetime: 2018-07-21T12:00:00.000Z whereas I would like the local-timezone time instead:
2018-07-21T14:00:00+0200
or
2018-07-21T14:00:00
How to get this (without relying on a third party dependency like momentjs)?
I tried this, which seems to work, but isn't there a more natural way to do it?
var pad = function(i) { return (i < 10) ? '0' + i : i; };
var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
Y = d.getFullYear();
m = d.getMonth() + 1;
D = d.getDate();
H = d.getHours();
M = d.getMinutes();
S = d.getSeconds();
s = Y + '-' + pad(m) + '-' + pad(D) + 'T' + pad(H) + ':' + pad(M) + ':' + pad(S);
console.log(s);
There is limited built-in support for formatting date strings with timezones in ECMA-262, there is either implementation dependent toString and toLocaleString methods or toISOString, which is always UTC. It would be good if toISOString allowed a parameter to specify UTC or local offset (where the default is UTC).
Writing your own function to generate an ISO 8601 compliant timestamp with local offset isn't difficult:
function toISOLocal(d) {
var z = n => ('0' + n).slice(-2);
var zz = n => ('00' + n).slice(-3);
var off = d.getTimezoneOffset();
var sign = off > 0? '-' : '+';
off = Math.abs(off);
return d.getFullYear() + '-'
+ z(d.getMonth()+1) + '-' +
z(d.getDate()) + 'T' +
z(d.getHours()) + ':' +
z(d.getMinutes()) + ':' +
z(d.getSeconds()) + '.' +
zz(d.getMilliseconds()) +
sign + z(off/60|0) + ':' + z(off%60);
}
console.log(toISOLocal(new Date()));
The trick is to adjust the time by the timezone, and then use toISOString(). You can do this by creating a new date with the original time and subtracting by the timezone offssetfrom the original time:
var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
var newd = new Date(d.getTime() - d.getTimezoneOffset()*60000);
console.log(newd.toISOString()); // 2018-07-21T22:00:00.000Z
Alternatively, you can simply adjust the original date variable:
var d = new Date("Sat Jul 21 2018 14:00:00 GMT+0200");
d = new Date(d.getTime() - d.getTimezoneOffset()*60000);
console.log(d.toISOString()); // 2018-07-21T22:00:00.000Z
For your convenience, the result from .getTime() is the number of milliseconds since 1 January 1970. However, getTimezoneOffset() gives a time zone difference from UTC in minutes; that’s why you need to multiply by 60000 to get this in milliseconds.
Of course, the new time is still relative to UTC, so you’ll have to ignore the Z at the end:
d = d.slice(0,-1); // 2018-07-21T22:00:00.000
My version:
// https://stackoverflow.com/questions/10830357/javascript-toisostring-ignores-timezone-offset/37661393#37661393
// https://stackoverflow.com/questions/49330139/date-toisostring-but-local-time-instead-of-utc/49332027#49332027
function toISOLocal(d) {
const z = n => ('0' + n).slice(-2);
let off = d.getTimezoneOffset();
const sign = off < 0 ? '+' : '-';
off = Math.abs(off);
return new Date(d.getTime() - (d.getTimezoneOffset() * 60000)).toISOString().slice(0, -1) + sign + z(off / 60 | 0) + ':' + z(off % 60);
}
console.log(toISOLocal(new Date()));
i have found a solution which has worked for me.
see this post: Modifying an ISO Date in Javascript
for myself i tested this with slight modification to remove the "T", and it is working. here is the code i am using:
// Create date at UMT-0
var date = new Date();
// Modify the UMT + 2 hours
date.setHours(date.getHours() + 2);
// Reformat the timestamp without the "T", as YYYY-MM-DD hh:mm:ss
var timestamp = date.toISOString().replace("T", " ").split(".")[0];
and an alternative method is stipulate the format you need, like this:
// Create the timestamp format
var timeStamp = Utilities.formatDate(new Date(), "GMT+2", "yyyy-MM-dd' 'HH:mm:ss");
note: these are suitable in locations that do not have daylight saving changes to the time during the year
it has been pointed out that the above formulas are for a specific timezone.
in order to have the local time in ISO format, first specify suitable Locale ("sv-SE" is the closest and easiest to modify), then make modification (change the space to a T) to be same as ISO format. like this:
var date = new Date(); // Create date
var timestamp = date.toLocaleString("sv-SE").replace(" ", "T").split(".")[0]; // Reformat the Locale timestamp ISO YYYY-MM-DDThh:mm:ss
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString)
https://www.w3schools.com/Jsref/jsref_tolocalestring.asp
https://www.w3schools.com/Jsref/tryit.asp?filename=tryjsref_tolocalestring_date_all
I have an API result giving out timestamp like this 1447804800000. How do I convert this to a readable format using Javascript/jQuery?
You can convert this to a readable date using new Date() method
if you have a specific date stamp, you can get the corresponding date time format by the following method
var date = new Date(timeStamp);
in your case
var date = new Date(1447804800000);
this will return
Wed Nov 18 2015 05:30:00 GMT+0530 (India Standard Time)
Call This function and pass your date :
JS :
function getDateFormat(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
var date = new Date();
date.toLocaleDateString();
return [day, month, year].join('-');
}
;
In my case, the REST API returned timestamp with decimal. Below code snippet example worked for me.
var ts= 1551246342.000100; // say this is the format for decimal timestamp.
var dt = new Date(ts * 1000);
alert(dt.toLocaleString()); // 2/27/2019, 12:45:42 AM this for displayed
I have written these two javascript functions:
function getDateFromDateAtHourOfDay(date, hour)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var newDate = new Date(year, month, day, hour, 0, 0);
return (newDate);
}
and
function getDateDescriptionFromDate(date)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
return ( (day < 10 ? ("0" + day) : (day)) + "." + (month < 10 ? ("0" + month) : (month)) + "." + year);
}
The first one should return a new date with the same year/month/day but with a different hour of the day (e.g. switch 2015-04-05 15:00 to 2015-04-05 16:00).
The second one should just return a date-string in the format dd.MM.yyyy.
Now if I call
var selectedDate = new Date(); // normally function parameter
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
document.getElementById("dateLabel").innerHTML = getDateDescriptionFromDate(startDate);
Where hour is a function parameter and for example 15 (tested with alert), in my "dateLabel" it says 05.01.2015. But if I do
alert (selectedDate);
the result is: Sun Apr 05 2015 15:52:26 GMT+0200 (CEST) => now.
selectedDate is not modified between the calls (alert and set the innerHTML).
I think the two functions do not do what I suppose them to, but maybe you find the mistake.
Thank you !
EDIT:
I tried this code:
selectedDate = new Date();
alert(selectedDate); // Sun Apr 05 2015 16:36:07 GMT+0200 (CEST)
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
alert(hour); // 8
alert(startDate); // Thu Mar 05 2015 08:00:00 GMT+0100 (CET)
document.getElementById("datumLabel").innerHTML = getDateDescriptionFromDate(startDate); // 05.01.2015
I don't know why you're surprised by what selectedDate is returning. You have only set it to new Date() (now). Nothing in the code is manipulating this variable from the point of creation.
You are, however, manipulating the value and storing the change in startDate and dateLabel.innerHTML. You would only notice the formatting though since the second function strips any change in "time" (done by the first function).
So, in short: You create a date (now), change the time, then format it to only show date.
var selectedDate = new Date();
//selectedDate value = the date and time right now
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
//startDate value = whatever selectedDate was + hours sent as parameter
document.getElementById("dateLabel").innerHTML = getDateDescriptionFromDate(startDate);
//Formatted value of startDate, to only show date
As per comment:
You're missing that month in javascript is zero-based. So you'll have to do something like:
var month = date.getMonth() + 1; //in the second function
function getDateFromDateAtHourOfDay(date, hour)
{
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var newDate = new Date(year, month, day, hour, 0, 0);
return (newDate);
}
function getDateDescriptionFromDate(date)
{
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
return ( (day < 10 ? ("0" + day) : (day)) + "." + (month < 10 ? ("0" + month) : (month)) + "." + year);
}
var selectedDate = new Date(); // normally function parameter
var startDate = getDateFromDateAtHourOfDay(selectedDate, 15);
document.getElementById("dateLabel").innerHTML = 'Your current system date: ' + getDateDescriptionFromDate(startDate);
<div id="dateLabel"></div>
If you try this, this should give you save value for your alert and Label, the value you are using for the Label is different than the value you are trying to use alert on.
selectedDate = new Date();
alert(selectedDate); // Sun Apr 05 2015 16:36:07 GMT+0200 (CEST)
var startDate = getDateFromDateAtHourOfDay(selectedDate, hour);
alert(hour); // 8
alert(startDate); // Thu Mar 05 2015 08:00:00 GMT+0100 (CET)
var startDateDesc = getDateDescriptionFromDate(startDate);
alert(startDateDesc) // 05.01.2015
document.getElementById("datumLabel").innerHTML = startDateDesc; // 05.01.2015
I need to increment a date value by one day in JavaScript.
For example, I have a date value 2010-09-11 and I need to store the date of the next day in a JavaScript variable.
How can I increment a date by a day?
Three options for you:
1. Using just JavaScript's Date object (no libraries):
My previous answer for #1 was wrong (it added 24 hours, failing to account for transitions to and from daylight saving time; Clever Human pointed out that it would fail with November 7, 2010 in the Eastern timezone). Instead, Jigar's answer is the correct way to do this without a library:
// To do it in local time
var tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
// To do it in UTC
var tomorrow = new Date();
tomorrow.setUTCDate(tomorrow.getUTCDate() + 1);
This works even for the last day of a month (or year), because the JavaScript date object is smart about rollover:
// (local time)
var lastDayOf2015 = new Date(2015, 11, 31);
console.log("Last day of 2015: " + lastDayOf2015.toISOString());
var nextDay = new Date(+lastDayOf2015);
var dateValue = nextDay.getDate() + 1;
console.log("Setting the 'date' part to " + dateValue);
nextDay.setDate(dateValue);
console.log("Resulting date: " + nextDay.toISOString());
2. Using MomentJS:
var today = moment();
var tomorrow = moment(today).add(1, 'days');
(Beware that add modifies the instance you call it on, rather than returning a new instance, so today.add(1, 'days') would modify today. That's why we start with a cloning op on var tomorrow = ....)
3. Using DateJS, but it hasn't been updated in a long time:
var today = new Date(); // Or Date.today()
var tomorrow = today.add(1).day();
var myDate = new Date();
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
The easiest way is to convert to milliseconds and add 1000*60*60*24 milliseconds e.g.:
var tomorrow = new Date(today.getTime()+1000*60*60*24);
Tomorrow in one line in pure JS but it's ugly !
new Date(new Date().setDate(new Date().getDate() + 1))
Here is the result :
Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)
None of the examples in this answer seem to work with Daylight Saving Time adjustment days. On those days, the number of hours in a day are not 24 (they are 23 or 25, depending on if you are "springing forward" or "falling back".)
The below AddDays javascript function accounts for daylight saving time:
function addDays(date, amount) {
var tzOff = date.getTimezoneOffset() * 60 * 1000,
t = date.getTime(),
d = new Date(),
tzOff2;
t += (1000 * 60 * 60 * 24) * amount;
d.setTime(t);
tzOff2 = d.getTimezoneOffset() * 60 * 1000;
if (tzOff != tzOff2) {
var diff = tzOff2 - tzOff;
t += diff;
d.setTime(t);
}
return d;
}
Here are the tests I used to test the function:
var d = new Date(2010,10,7);
var d2 = AddDays(d, 1);
document.write(d.toString() + "<br />" + d2.toString());
d = new Date(2010,10,8);
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 27 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, 1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
d = new Date('Sun Mar 28 2011 01:59:00 GMT+0100 (CET)');
d2 = AddDays(d, -1)
document.write("<hr /><br />" + d.toString() + "<br />" + d2.toString());
You first need to parse your string before following the other people's suggestion:
var dateString = "2010-09-11";
var myDate = new Date(dateString);
//add a day to the date
myDate.setDate(myDate.getDate() + 1);
If you want it back in the same format again you will have to do that "manually":
var y = myDate.getFullYear(),
m = myDate.getMonth() + 1, // january is month 0 in javascript
d = myDate.getDate();
var pad = function(val) { var str = val.toString(); return (str.length < 2) ? "0" + str : str};
dateString = [y, pad(m), pad(d)].join("-");
But I suggest getting Date.js as mentioned in other replies, that will help you alot.
I feel that nothing is safer than .getTime() and .setTime(), so this should be the best, and performant as well.
const d = new Date()
console.log(d.setTime(d.getTime() + 1000 * 60 * 60 * 24)) // MILLISECONDS
.setDate() for invalid Date (like 31 + 1) is too dangerous, and it depends on the browser implementation.
Getting the next 5 days:
var date = new Date(),
d = date.getDate(),
m = date.getMonth(),
y = date.getFullYear();
for(i=0; i < 5; i++){
var curdate = new Date(y, m, d+i)
console.log(curdate)
}
Two methods:
1:
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setTime(a.getTime() + no_of_days * 86400000)
2: Similar to the previous method
var a = new Date()
// no_of_days is an integer value
var b = new Date(a.setDate(a.getDate() + no_of_days)
Via native JS, to add one day you may do following:
let date = new Date(); // today
date.setDate(date.getDate() + 1) // tomorrow
Another option is to use moment library:
const date = moment().add(14, "days").toDate()
Get the string value of the date using the dateObj.toJSON() method Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
Slice the date from the returned value and then increment by the number of days you want.
var currentdate = new Date();
currentdate.setDate(currentdate.getDate() + 1);
var tomorrow = currentdate.toJSON().slice(0,10);
Date.prototype.AddDays = function (days) {
days = parseInt(days, 10);
return new Date(this.valueOf() + 1000 * 60 * 60 * 24 * days);
}
Example
var dt = new Date();
console.log(dt.AddDays(-30));
console.log(dt.AddDays(-10));
console.log(dt.AddDays(-1));
console.log(dt.AddDays(0));
console.log(dt.AddDays(1));
console.log(dt.AddDays(10));
console.log(dt.AddDays(30));
Result
2017-09-03T15:01:37.213Z
2017-09-23T15:01:37.213Z
2017-10-02T15:01:37.213Z
2017-10-03T15:01:37.213Z
2017-10-04T15:01:37.213Z
2017-10-13T15:01:37.213Z
2017-11-02T15:01:37.213Z
Not entirelly sure if it is a BUG(Tested Firefox 32.0.3 and Chrome 38.0.2125.101), but the following code will fail on Brazil (-3 GMT):
Date.prototype.shiftDays = function(days){
days = parseInt(days, 10);
this.setDate(this.getDate() + days);
return this;
}
$date = new Date(2014, 9, 16,0,1,1);
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
$date.shiftDays(1);
console.log($date+"");
Result:
Fri Oct 17 2014 00:01:01 GMT-0300
Sat Oct 18 2014 00:01:01 GMT-0300
Sat Oct 18 2014 23:01:01 GMT-0300
Sun Oct 19 2014 23:01:01 GMT-0200
Adding one Hour to the date, will make it work perfectly (but does not solve the problem).
$date = new Date(2014, 9, 16,0,1,1);
Result:
Fri Oct 17 2014 01:01:01 GMT-0300
Sat Oct 18 2014 01:01:01 GMT-0300
Sun Oct 19 2014 01:01:01 GMT-0200
Mon Oct 20 2014 01:01:01 GMT-0200
Results in a string representation of tomorrow's date. Use new Date() to get today's date, adding one day using Date.getDate() and Date.setDate(), and converting the Date object to a string.
const tomorrow = () => {
let t = new Date();
t.setDate(t.getDate() + 1);
return `${t.getFullYear()}-${String(t.getMonth() + 1).padStart(2, '0')}-${String(
t.getDate()
).padStart(2, '0')}`;
};
tomorrow();
Incrementing date's year with vanilla js:
start_date_value = "01/01/2019"
var next_year = new Date(start_date_value);
next_year.setYear(next_year.getYear() + 1);
console.log(next_year.getYear()); //=> 2020
Just in case someone wants to increment other value than the date (day)
Timezone/daylight savings aware date increment for JavaScript dates:
function nextDay(date) {
const sign = v => (v < 0 ? -1 : +1);
const result = new Date(date.getTime());
result.setDate(result.getDate() + 1);
const offset = result.getTimezoneOffset();
return new Date(result.getTime() + sign(offset) * offset * 60 * 1000);
}
This a simpler method ,
and it will return the date in simple yyyy-mm-dd format , Here it is
function incDay(date, n) {
var fudate = new Date(new Date(date).setDate(new Date(date).getDate() + n));
fudate = fudate.getFullYear() + '-' + (fudate.getMonth() + 1) + '-' + fudate.toDateString().substring(8, 10);
return fudate;
}
example :
var tomorrow = incDay(new Date(), 1); // the next day of today , aka tomorrow :) .
var spicaldate = incDay("2020-11-12", 1); // return "2020-11-13" .
var somedate = incDay("2020-10-28", 5); // return "2020-11-02" .
Note
incDay(new Date("2020-11-12"), 1);
incDay("2020-11-12", 1);
will return the same result .
Use this function, it´s solved my problem:
let nextDate = (daysAhead:number) => {
const today = new Date().toLocaleDateString().split('/')
const invalidDate = new Date(`${today[2]}/${today[1]}/${Number(today[0])+daysAhead}`)
if(Number(today[1]) === Number(12)){
return new Date(`${Number(today[2])+1}/${1}/${1}`)
}
if(String(invalidDate) === 'Invalid Date'){
return new Date(`${today[2]}/${Number(today[1])+1}/${1}`)
}
return new Date(`${today[2]}/${Number(today[1])}/${Number(today[0])+daysAhead}`)
}
Assigning the Increment of current date to other Variable
let startDate=new Date();
let endDate=new Date();
endDate.setDate(startDate.getDate() + 1)
console.log(startDate,endDate)