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
Related
This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 2 years ago.
var today = new Date();
var tomorrow = today.setDate(today.getDate() + 1)
console.log(tomorrow)
1596607917318
I am getting 13 digit number after using setDate(). How can I get the date in 2 digit format?
Date outputs in JS often need some manual processing to be exactly what you want. Try this:
// Create new Date instance
var today = new Date();
var tomorrow = today;
// Add a day
tomorrow.setDate(tomorrow.getDate() + 1)
console.log(formatDateToString(tomorrow));
function formatDateToString(date) {
var dd = (date.getDate() < 10 ? '0' : '')
+ date.getDate();
var MM = ((date.getMonth() + 1) < 10 ? '0' : '')
+ (date.getMonth() + 1);
return dd + "/" + MM;
}
The Date object has different methods that you can use to get certain parts of the timestamp.
// for day-month (i.e.: Oct 31 is 31-10
let formatted = `${tomorrow.getDate()}-${tomorrow.getMonth() + 1}`
See more: https://www.w3schools.com/js/js_date_formats.asp
setDate has changed the date of today.
Therefore output today and don't assign what's returned by setDate.
var today = new Date();
today.setDate(today.getDate() + 1);
console.log(today.toLocaleDateString());
Month is zero based so getMonth() + 1 returns this month, getDate() + 1 returns tomorrow.
var fecha = new Date();
var year = fecha.getFullYear();
var mes = fecha.getMonth() + 1;
var dia = fecha.getDate() + 1;
var hora = fecha.getHours();
var minutos = fecha.getMinutes();
var segundos = fecha.getSeconds();
var output = `Date: ${dia}/${mes}/${year}`+ '\n' + `Time: ${hora}:${minutos}:${segundos}`;
console.log(output)
Nice question, I recently had to do something similar in VB. Here is a simple javascript version, based on your code:
//this gets the date today
var today = new Date();
//we add one, to get the date tomorrow
var tomorrow = today.getDate() + 1
//if tomorrow is a single digit number, we just pad it with a zero
if (tomorrow < 10)
{
tomorrow = '0' + tomorrow
}
//write to the console
console.log(tomorrow)
I wrote the following code in JS
var d = new Date(2019, 9, 14);
var currentTime = d.getTime();
var daysToAdd = 3;
var secondsInDay = 86400;
var d = new Date(currentTime + daysToAdd*secondsInDay);
var year = d.getFullYear();
var month = ("0" + (d.getMonth())).slice(-2);
var day = ("0" + d.getDate()).slice(-2);
console.log('result in Y-M-D is: ' + year + '-' + month + '-' + day);
This outputs to result in Y-M-D is: 2019-09-14
What am I doing wrong here? How to I change this to output result in Y-M-D is: 2019-09-17 , which I originally intended to do
This happens because on this code
new Date(currentTime + daysToAdd*secondsInDay);
secondsInDay is a representation in seconds, and currentTime is represented in ms. If you multiply your secondsInDay by 1000 (to get the equivalent value in ms) you will get the desired date.
Instead of
var d = new Date(currentTime + daysToAdd*secondsInDay);
you can use
d.setDate(new Date().getDate()+3);
Youre problem is that the constructor of the date object uses MILISECONDS to calculate the date, and you're using SECONDS to add that 3 extra days. Instead of 86400 (seconds) you need to use the value 86400000 (miliseconds).
Goodbye!
You can add the number of days directly to d.getDate()
var d = new Date(2019, 9, 14);
var daysToAdd = 3;
var new_day = d.getDate() + daysToAdd;
var new_d = new Date(d.getFullYear(), d. getMonth(), new_day);
alert('result in Y-M-D is: ' + new_d.getFullYear() + '-' + new_d. getMonth() + '-' + new_day);
<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);
I'm having two dates given below with the format for which I need to get the number of months that are there in between them.I tried Difference in months between dates in Javascript :
but the format is not matching with the one that I have.Can anybody suggest a fix please?
startDate:"2015-09-07",
endDate: "2015-12-30"
Also I need to display the months that are there in between the dates like:
var months=["sept","oct","nov","dec","jan","feb"]
Well, you could always split string and use month like this:
var startDate = startDate.split("-");
var endDate= endDate.split("-");
var MonthDifference = endDate[1] - startDate[1];
So you could for example do this function:
function DifferenceInMonths(startDate, endDate){
startDate= startDate.split("-");
endDate= endDate.split("-");
return endDate[1] - startDate[1];
}
But then we are facing problem where these dates could happen in 2 different years. What if you would try this:
function differenceCalculatedInMonthsByUnix(startDate, endDate){
startDate = new Date(startDate).getTime();
endDate= new Date(endDate).getTime();
var difference = endDate - startDate;
return timeMe(difference);
}
function timeMe(unix_timestamp){
unix_timestamp = parseInt(unix_timestamp);
var date = new Date(unix_timestamp);
var days = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear()
// hours part from the timestamp
var hours = date.getHours();
// minutes part from the timestamp
var minutes = "0" + date.getMinutes();
// seconds part from the timestamp
var seconds = "0" + date.getSeconds();
// will display time in 10:30:23 format
var formattedTime = days + '.' + month + '.' + year + ' at:' + hours + ':' + minutes.substr(minutes.length-2) + ':' + seconds.substr(seconds.length-2);
return (12 * year) + month
}
Not sure did i do that TimeMe() my self or did i find it from stackOverflow so if some one needs credits, pm me.
But yea the idea in this is, that we turn date into unix time stamp, calculate difference, and turn it into months.
this is my code:
var currentTime = new Date()
var month = currentTime.getMonth() + 1
var day = currentTime.getDate()
var year = currentTime.getFullYear()
var hours = currentTime.getHours()
var minutes = currentTime.getMinutes()
alert(minutes+"/"+hours+"/"+month + "/" + day + "/" + year)
but , i think it hard to compare with two time ,
what can i do ?
thanks
If you really want to know whether two Date objects represent precisely the same time, or are before/after one another, it's quite easy: just compare the two Dates via the getTime() method, which returns an integer timestamp for the object. For example,
var date1 = myDate,
date2 = new Date();
return (date1.getTime() < date2.getTime());
would return true if myDate is before 'now', false if it is now or in the future.