Subtracting a Day from a Full Date - javascript

I need to subtract 1 day from a string value of a date I have,
for example when I subtract a day from 2017/01/01 instead of getting 2016/12/31 I end up getting a value of 2017/0/31.
Below is the code I'm working on:
var inputDate = "2017/01/01";
var splitClndr = inputDate.value.split("/");
var clndrDate = new Date(splitClndr[0], splitClndr[1], splitClndr[2]);
clndrDate.setDate(clndrDate.getDate() - 1);
var nd = new Date(clndrDate);
var dd = nd.getDate();
var mm = nd.getMonth();
var y = nd.getFullYear();
var newFormattedDate = y + '/'+ mm + '/'+ dd;
operatorDate.value = newFormattedDate;
The value I get in the variable newFromattedDate is 2017/0/31, how can I make the result of subtracting a day to 2016/12/31 instead?

Months in javascript are zero-based, so 0 is January:
new Date(2017, 1, 1) >> Wed Feb 01 2017
You need to compensate for this, both when creating your clndrDate and when concatenating your string.
new Date(splitClndr[0], splitClndr[1]-1, splitClndr[2])
...
var mm = nd.getMonth()+1;

You can just substract directly from the date:
var d = new Date('2017/01/01');
d.setDate(d.getDate() - 1);
var newDateString = d.toLocaleDateString();
console.log(newDateString);

You can use setDate method to subtract the number of days you want.
var inputDate = "2017/01/01";
var newDate = new Date(inputDate);
newDate.setDate(newDate.getDate() - 1);
console.log(newDate);

Try this,
var inputDate = "2017/01/01";
var splitClndr = inputDate.split("/");
var clndrDate = new Date(splitClndr[0], splitClndr[1] - 1, splitClndr[2]);
var past_time = clndrDate.getTime() - 1000 * 60 * 60 * 24 * 1; // last 1 will be day
clndrDate.setTime(past_time);
console.log(clndrDate);
Working jsfilddle.

Related

round up hour difference in time to 2 decimal places with javascript

i'm trying to calculate the hours difference between to times using javascript. But i keep get the results NaN in the console. I get the current time using javascript and the late time from the localstorage
var log_time = localStorage.getItem('login_time')
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
console.log(log_time);
var today = day + "/" + month + "/" + year
var time = hour + ":" + minute + ":" + second
console.log(today+' '+time);
var date1 = (log_time);
var date2 = (today+' '+time);
var hours = Math.abs(date2 - date1) / 36e5;
console.log(hours.toFixed(2))
the time from the localstorage reads 15/7/2017 9:30:46
You need to change your date format little bit This may Help you and also parse those dates because those are stirng formate.
Working Fiddle
var log_time1 = '2017-07-15 09:30:46';//Examples of ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS.
var log_time = new Date(log_time1)//string parsing date
var currentDate = new Date()
var day = currentDate.getDate()
var month = currentDate.getMonth() + 1
var year = currentDate.getFullYear()
var hour = currentDate.getHours(); // => 9
var minute= currentDate.getMinutes(); // => 30
var second= currentDate.getSeconds(); // => 51
var today = year + "-" + month + "-" + day
var time = hour + ":" + minute + ":" + second
var date1 = (log_time);
var test_date2 = (today+' '+time);
var date2= new Date(test_date2);//string parsing date
var hours = Math.abs(date2 - date1) / 36e5;
alert(hours.toFixed(2))
localStorage will store stringified version of any object, you need to parse it. If you converted it to milliseconds then also you need to parse it to number, it can save only string
var earlierDate = new Date( localStorage.getItem('login_time'))
// or var earlierDate = parseInt(localStorage.getItem('login_time'))
var currentDate = new Date()
var diff = currentDate - earlierDate;
Then convert diff to hour/minutes/seconds with your logic
Im not shure what youre trying to do here:
date2 - date1
These are booth strings, you cannot substract them. However you might convert them to milliseconds since 1970 which you could then do Math on:
var log_time = localStorage.getItem('login_time').split(" ");
log_time[0]=log_time[0].split("/").reverse().map((el,i)=>i?("0"+el).slice(-2):el).join("-");//5/4/2017 => 2017-04-05
log_time[1]=("0"+log_time[1]).slice(-8);// 9:30:10 => 09:30:10
var difference= new Date() - new Date(log_time.join("T"));
var hours=Math.floor(difference/(1000*60*60 /* one hour in ms */));
You may overthink the stored format. Its quite complicated to parse it properly.
http://jsbin.com/fofowayata/edit?console

Javascript setDate doesnt accept input

<code>
var d2 = $('#interval').val();
var new_date = new Date(get_start_date);
new_date.setDate(new_date.getDate() + d2);
var dd = new_date.getDate();
var mm = new_date.getMonth() + 1;
var y = new_date.getFullYear();
var endDate = y + '-' + mm + '-' + dd;
</code>
assuming d2 = 5
when im adding 5 dates to my current date, its not returning exact answer instead its adding months it becomes 2017-09-09
but when i just do this new_date.setDate(new_date.getDate() + 5) it gives me the correct output.
Just parse you d2 as an integer
var d2 = parseInt($('#interval').val(),10);
u can only use this arguments
new Date()
new Date(milliseconds)
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)
get_start_date is invailid ;)
var new_date = new Date(get_start_date);

Why its not giving me the correct total month?

Why it's not giving me the correct total month? (with compared to current mm-yyyy)
function get_total_month(mm,yyyy) {
// custom inputs
var start_date = new Date(yyyy, mm, 01);
// current date
var today_date = new Date();
var today_year = today_date.getFullYear();
var today_month = today_date.getMonth();
var today_day = today_date.getDate();
var end_date = new Date(new Date(today_year, today_month, today_day));
// compare the given date with current date to find the total months
var total_months = (end_date.getFullYear() - start_date.getFullYear())*12 + (end_date.getMonth() - start_date.getMonth());
return total_months;
}
alert(
get_total_month(01, 2014)
);
Giving me: 20 instead of 22
That's because the Date.prototype.getMonth method returns a 0-11 number. So:
January = 0
February = 1
...
December = 11
I think this is what you are looking for, it is another version of your code. But I think is shorter and easier to understand. What do you think?
(I added the +2 to adjust the result to what you are expecting the function to return)
function monthDifference(startDate) {
var months;
var currentDate = new Date();
months = (currentDate.getFullYear() - startDate.getFullYear()) * 12;
months -= startDate.getMonth() + 1;
months += currentDate.getMonth();
return months <= 0 ? 0 : (months + 2);
}
alert(monthDifference(new Date(2014,0)) );
alert(monthDifference(new Date(2013,11)) );

i am using datetime picker and want that my start and end date must have difference of 24 hours

Start time is :- 02/18/2014 11:00
End time is :-02/27/2014 09:33
I want to calculate the difference between 2 dates using jquery
so that I can add validation that user must keep the difference of 24 hour (1day) while selecting the date.
this is the jquery
var start = new Date("2014-02-18");
var end = new Date();
var diff = new Date(end - start);
var days = diff/1000/60/60/24
//alert(days);
if(days<=1){
alert("less then 1 day");
}
else{
alert("more then 1 day");
}
this is the jsfiddle for it
http://jsfiddle.net/3QAJa/5/
var start_actual_time = "02/18/2014 11:00";
var end_actual_time = "02/27/2014 09:33";
start_actual_time = new Date(start_actual_time);
end_actual_time = new Date(end_actual_time);
var diff = end_actual_time - start_actual_time;
var diffSeconds = diff/1000;
var HH = Math.floor(diffSeconds/3600);
var MM = Math.floor(diffSeconds%3600)/60;
var formatted = ((HH < 10)?("0" + HH):HH) + ":" + ((MM < 10)?("0" + MM):MM)
alert(formatted);

how to get difference in year where dates are in yyyy-mm-dd?

i want to get the difference between two dates which are give in yyyy-mm-dd format difference should be in year.
var ds='2002-09-23';
var today_date = new Date();
alert(today_date);
Date.prototype.yyyymmdd = function() {
var mm = (this.getMonth()+1).toString(); // getMonth() is zero-based
var dd = this.getDate().toString();
var dt = yyyy +"-"+(mm[1]?mm:"0"+mm[0]) +"-"+ (dd[1]?dd:"0"+dd[0]);// padding
var num_years = diff_date/31536000000;
alert(num_years);
if (num_years>18){
alert (num_years);
}else{
alert ("i m not 18");
}
please help me out.
This is much shorter:
var yearsApart = new Date(new Date - new Date('2002-09-23')).getFullYear()-1970
… but be careful to take care of non UTC time zones by providing the correct datetime string!
You need no library for this, just pure javascript:
function wholeYearsBetweenTwoDates(dateOneString, dateTwoString) {
// assuming that dateTwo is later in time than dateOne
var dateOne = getDateFromString(dateOneString);
var dateTwo = getDateFromString(dateTwoString);
var result = dateTwo.getFullYear() - dateOne.getFullYear();
dateOne.setFullYear(dateTwo.getFullYear());
if (dateOne > dateTwo) {
// compensate for the case when last year is not full - e.g., when
// provided with '2009-10-10' and '2010-10-09', this will return 0
result -= 1;
}
return result;
}
function getDateFromString(stringDate) {
var dateParts = stringDate.split('-');
var result = new Date(dateParts[0], dateParts[1], dateParts[2]);
return result;
}
Try the following code to get the difference in years...
function getDateDiffInYears(date1, date2) {
var dateParts1 = date1.split('-')
, dateParts2 = date2.split('-')
, d1 = new Date(dateParts1[0], dateParts1[1]-1, dateParts1[2])
, d2 = new Date(dateParts2[0], dateParts2[1]-1, dateParts2[2])
return new Date(d2 - d1).getYear() - new Date(0).getYear() + 1;
}
var diff = getDateDiffInYears('2005-09-23', '2012-07-3');
console.log(diff); // => 7 years
Good luck!
I had been using the formula var yearsApart=milli/milliPerYear but when the day and the month are the same the rounded value is not correct.
Here you have the script I'm using right now ...
function yearDifferenceDates(firstDateDay, firstDateMonth, firstDateYear, secondDateDay, secondDateMonth, secondDateYear) {
var fisrtDate = new Date(firstDateYear, firstDateMonth - 1, firstDateDay);
var secondDate = new Date(secondDateYear, secondDateMonth - 1, secondDateDay);
if(firstDateDay == secondDateDay && (firstDateMonth - 1) == (secondDateMonth - 1)) {
return Math.round((secondDate-fisrtDate)/(1000*60*60*24*365.242199));
}
return Math.floor((secondDate-fisrtDate)/(1000*60*60*24*365.242199));
}
First you have to pick a JavaScript library for parsing dates using a format string (so you can provide date in the format you prefer). Try this great library (at least you do not have to care about implementation details. Date constructor and Date.parse methods must match but it's not mandatory they can parse a simple date in that format).
var date1 = getDateFromFormat("1999-10-10", "YYYY-MM-DD");
var date2 = getDateFromFormat("2012-10-10", "YYYY-MM-DD");
Then, when you have to calculate the difference:
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60;
var millisecondsPerHour = millisecondsPerMinute * 60;
var millisecondsPerDay = millisecondsPerHour * 24;
var millisecondsPerYear = millisecondsPerDay * 365.26;
var years = Math.round((date2 - date1) / millisecondsPerYear);
If you need a raw calculation you can use getFullYear() directly.
You can compare dates more easily if you convert them to their millisecond values.
var birthday = new Date('2002-09-23');
var now = new Date();
var age = now.getTime() - birthday.getTime();
if (age < (1000 * 60 * 60 * 24 * 365 * 18)) { // number of milliseconds in 18 years
document.write('not over 18');
} else {
document.write('over 18');
}
Above has a little bug but this work :)
NOT WORKING: var millisecondsPerHour = millisecondsPerMinute = 60;
WORKING FINE: var millisecondsPerHour = millisecondsPerMinute * 60;
But thx Adriano Repetti
Here the complete code (with dot Format)
var date1 = "01.01.2014";
var date2 = "31.12.2016";
var date1 = date1.split(".");
var date2 = date2.split(".");
date1 = String(date1[2] +"-"+ date1[1] +"-"+ date1[0]);
date2 = String(date2[2] +"-"+ date2[1] +"-"+ date2[0]);
var date1 = Date.parse(date1);
var date2 = Date.parse(date2);
//(Not for Europa :) )
//var date1 = Date.parse("2014-01-01");
//var date2 = Date.parse("2016-12-31");
var millisecondsPerSecond = 1000;
var millisecondsPerMinute = millisecondsPerSecond * 60;
var millisecondsPerHour = millisecondsPerMinute * 60;
var millisecondsPerDay = millisecondsPerHour * 24;
var millisecondsPerYear = millisecondsPerDay * 365.26;
// IN YEARS
var years = (date2 - date1) / millisecondsPerYear;
// IN MONTHS
var month = years * 12 // Very tricky, I know ;)
var d1=new Date(2002, 9, 23);
var d2=new Date();
var milli=d2-d1;
var milliPerYear=1000*60*60*24*365.26;
var yearsApart=milli/milliPerYear;
console.log(yearsApart)

Categories