This question already has answers here:
Add one day to date in javascript
(11 answers)
Closed 4 years ago.
I have From-Date, To-Date, and Total-Days...if i have a From-Date and Total-Days then i have to calculate To-Date automatically
I Used The Following method to get the To-Date day
var FromDate = $("#FromDate").val();
var TotalDays = $("#txtDays").val();
FromDate.setDate(parseInt(FromDate.getDate()) + parseInt(NoOfDays));
var dd = FromDate.getDate()-1;
This Will Not Work For Day 1 of every month.....Since It Returns 0
How To Handle This Situation or help me to solve this in another way....Thanx In Advance
try this
var d = new Date('08-20-2018');
d.setDate(d.getDate() - 1);
alert(d.getDate());
Date object is smart enough to know what to do if you set any of the "components" (month, day, hour, minute, second, millisecond) outside of "normal" range - it does the maths for you
If you only need to know the previous date, you can always subtract the 24hours from the epoch time and then convert it back to date object and get the date like:
new Date(new Date('08-01-2018').getTime() - 24*3600000).getDate()
new Date('08-01-2018').getTime() will give you the epoch time of the date you want previous date from
24*3600000 is subtracting the 24 milliseconds from the epoch
After subtracting the value you get the previous day epoch and using the new Date() constructor you are getting the Date object again
On this new date object you can call getDate() method to get the correct result of 31.
I have given date to Date constructor in MM-DD-YYYY format
Related
This question already has answers here:
How to add days to Date?
(56 answers)
Closed 1 year ago.
I know that a sample date object in javascript is constructed from a string containing the year, month and day. I am building a function that takes a date and number of days as arguments and adds the days to the date and returns a new date object from the same.
The approach i used is this:
a) Get the milliseconds from the date object
b) Convert the days to milliseconds
c) Add the two and then derive a date object from the resultant sum.
I need a way to get back to the date from the milliseconds. Thank You for your help
function AddDays(x,y){
//convert the days to milliseconds
let days_milli=y*24*60*60*1000;
//get the time in millis from the date
let days_millis=x.getTime();
//add the times
let total=days_milli+days_millis;
//construct a date object from that
//this line needs some help
let date=getDate(total);
return date;
}
Looks like the Date class constructor has overloads to support construction of objects from a string and milliseconds. All i needed to do was to invoke new Date and then put the milliseconds in the parameter part.
function AddDays(x,y){
//convert the days to milliseconds
let days_milli=y*24*60*60*1000;
//get the time in millis from the datw
let days_millis=x.getTime();
//add the times
let total=days_milli+days_millis;
//construct a date object from that
let date=new Date(total);
return date;
}
This question already has answers here:
How to calculate date difference in JavaScript? [duplicate]
(24 answers)
Closed 4 years ago.
I have been trying to calculate the exact time since a very specific date in history using Javascript.
The Date is Feb 24th 2008 17:30 GMT+0
I need help in calculating exact time passed down to the second using Javascript.
Here is the previous date and the current date.
I need help in calculating Hours, Minutes and Seconds since that date/time.
var previousDate = new Date("Sun Feb 24 2008 17:30:00 GMT+0");
var currentDate = new Date();
It's easy to calculate the milliseconds between two dates:
var millis = currentDate - previousDate;
From there you can calculate the seconds:
var seconds = Math.round(millis / 1000);
Calculation of minutes, hours, ... is straightforward (division by 60 or 60*60).
Parsing of date strings in javascript fraught. If you have a specific date, far better to avoid the built–in parser. If it's UTC, use Date.UTC to generate the time value.
Then just subtract from any other date to get the difference in milliseconds and convert to seconds, as hgoebi suggests.
var epoch = new Date(Date.UTC(2008,1,24,17,30));
console.log(epoch.toISOString());
console.log(`Seconds from epoch to now: ${(Date.now() - epoch)/1000|0}`);
This question already has answers here:
Why does Date.parse give incorrect results?
(11 answers)
Changing the format of a date string
(2 answers)
Closed 5 years ago.
I am trying to use a simple date function in my application to pass a date in the format of yyyy-mm-dd such as 2017-07-30 and have it returned in the format of 07/30/2017.
However, when I try this, I supply my date correctly but it outputs one day shorter than what I am looking for.
function format(inputDate) {
var date = new Date(inputDate);
if (!isNaN(date.getTime())) {
var day = date.getDate().toString();
var month = (date.getMonth() + 1).toString();
// Months use 0 index.
return (month[1] ? month : '0' + month[0]) + '/' +
(day[1] ? day : '0' + day[0]) + '/' +
date.getFullYear();
}
}
console.log(format('2017-07-30'));
Here is a fiddle: http://jsfiddle.net/49pptrj4/
Any thoughts as to why this is returning incorrectly?
Result on my end:
From here
Given a date string of "March 7, 2014", [Date.]parse() assumes a local time zone, but given an ISO format such as "2014-03-07" it will assume a time zone of UTC.
Your date string is assumed to be 0:00, or midnight, on the date specified in UTC, the time zone of Greenwich, England. Your browser however takes this time and converts it to your local timezone, which is a few hours behind UTC if you're in the Americas, making the result a day behind.
The following code should work for creating a Date in the local timezone with the correct date.
utcDate = new Date("2017-07-30"); //Date object a day behind
new Date(utcDate.getTime() + utcDate.getTimezoneOffset() * 60000) //local Date
Here the local Date is created by adding time based on the time zone difference. getTimezoneOffset() returns in minutes, so * 60000 is needed to convert to milliseconds.
This might not work in areas ahead of UTC; it might advance an extra day.
Edit: Just checked and getTimezoneOffset() is negative in areas ahead of UTC so it will subtract time correctly.
I'm currently just practising JavaScript and I'm trying to create a programme that calculates how many days there are until your next birthday.
I have seen on this site that there is a daysBetween function that I can use to tell the time difference between two dates (I just need to turn these dates into the millisecond value since the 1st Jan 1970).
The problem is that, although one of those dates is the current date (which is easy to convert into its millisecond value), the second is derived from answers the user inputs as a string into a prompt command (there are three different boxes that ask for the year, month and date of their birth). Is there a way I can convert these input strings into a date format that I can then use to find the days between today's date and their next birthday?
Thanks and sorry if this is a stupid question!
Remember in JS that months are indexed from 0, so January === 0.
var date = new Date('2017','5','25'); would be today, assume you have something like:
var userDd = '25';
var userMm = '6'; // User doesn't know the months are indexed at 0.
var userYy = '2017';
var date = new Date(userYy, userMm - 1, userYy);
date.getTime(); // returns the milliseconds value.
I'm working on a response from a script to work out an expiry date. The response is 7200 which I've been advised from the developer is an epoch value that should equate to 3 months. I've never used Epoch before so don't understand how this works?
The formula I've been given to use is (created_at + expires_in) * 1000 which I've been advised will give me my new date.
I used dtmNow = new Date(Date.now()).toISOString(); which returned 2016-08-23T06:33:35.936Z which was correct, but when I tried dtmExpires = new Date((Date.now()+7200)*1000).toISOString(); it returned +048613-09-25T09:58:58.000Z?
I'm not sure what I'm doing wrong here?
Date.now() returns the number of milliseconds since the epoch (the current time value). If you pass a number to the Date constructor, it's used as the time value for a new Date instance. In the following:
new Date(Date.now()).toISOString()
is exactly the same as:
new Date().toISOString()
i.e. you don't need Date.now(). If you want to add 3 months to a date, use Date methods:
// Get a Date for now
var now = new Date();
// Add 3 months
now.setMonth(now.getMonth() + 3);
However, if it's currently 30 November then the above will attempt to create a date for 30 February, which will end up being 1 or 2 March depending on whether it's a in a leap year or not. So if the modified day in the month doesn't match the original, you can set it back to the last day of the previous month.
If you want to add (say) 90 days, then do that using the setDate and getDate methods similar to the following. This also takes account of daylight saving boundaries if you cross one, whereas setting the time value doesn't.
The SO console writes dates in UTC so take that into account when looking at the following results:
function add3Months(d) {
// Default to current date if d not provided
d = d || new Date();
// Remember current date
var date = d.getDate();
// Add 3 months
d.setMonth(d.getMonth() + 3);
// Set the date back to the last day of the previous
// month if date isn't the same
if (d.getDate() != date) d.setDate(0);
return d;
}
// Add 3 months to today
console.log(add3Months());
// Add 3 months to 30 November
console.log(add3Months(new Date(2016,10,30)))