Time between two times on current date - javascript

I am trying to calculate the time between two times on the current date using JavaScript. There are other questions similar to this one, but none seem to work, and few with many upvotes that I can find.
I have the following, which fails on the line: var diff = new Date(time1 - time2);, which always gives me an invalid Date when alerted, so it is clearly failing. I cannot work out why.
The initial date is added in the format of: hh:mm:ss in an input field. I am using jQuery.
$(function(){
$('#goTime').click(function(){
var currentDate = new Date();
var dateString = (strpad(currentDate.getDate()) +'-'+ strpad(currentDate.getMonth()+1)+'-'+currentDate.getFullYear()+' '+ $('#starttime').val());
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = new Date(time1 - time2);
var hours = diff.getHours();
var minutes = diff.getMinutes();
var seconds = diff.getMinutes();
alert(hours + ':' + minutes + ':' + seconds);
});
});
function strpad(val){
return (!isNaN(val) && val.toString().length==1)?"0"+val:val;
}
dateString is equal to: 14-01-2013 23:00

You have the fields in dateString backwards. Swap the year and day fields...
> new Date('14-01-2013 23:00')
Invalid Date
> new Date('2013-01-14 23:00')
Mon Jan 14 2013 23:00:00 GMT-0800 (PST)

dd-MM-yyyy HH:mm is not recognized as a valid time format by new Date(). You have a few options though:
Use slashes instead of dashes: dd/MM/yyyy HH:mm date strings are correctly parsed.
Use ISO date strings: yyyy-MM-dd HH:mm are also recognized.
Build the Date object yourself.
For the second option, since you only really care about the time, you could just split the time string yourself and pass them to Date.setHours(h, m, s):
var timeParts = $('#starttime').val().split(':', 2);
var time1 = new Date();
time1.setHours(timeParts[0], timeParts[1]);

You are experiencing an invalid time in your datestring. time1 is NaN, and so diff will be. It might be better to use this:
var date = new Date();
var match = /^(\d+):(\d+):(\d+)$/.exec($('#starttime').val()); // enforcing format
if (!match)
return alert("Invalid input!"); // abort
date.setHours(parseInt(match[1], 10));
date.setMinutes(parseInt(match[2], 10));
date.setSeconds(parseInt(match[3], 10));
var diff = Date.now() - date;

If you are trying to calculate the time difference between two dates, then you do not need to create a new date object to do that.
var time1 = new Date(dateString).getTime();
var time2 = new Date().getTime();
var diff = time1 - time2;// number of milliseconds
var seconds = diff/1000;
var minutes = seconds/60;
var hours = minutes/60;
Edit: You will want to take into account broofa's answer as well to
make sure your date string is correctly formatted
The getTime function returns the number of milliseconds since Jan 1, 1970. So by subtracting the two values you are left with the number of milliseconds between each date object. If you were to pass that value into the Date constructor, the resulting date object would not be what you are expecting. see getTime

Related

Javascript subtract one day from "yyyy-mm-ss" string IN UTC TIMEZONE

I have a string for a UTC date var latestDate='2020-11-17' , and I'm trying to get the previous days date from this string into a new variable var subtractedDate;.
So my goal is to get subtractedDate=2020-11-16
var latestDate='2020-11-17';
//convert to iso date string
var dateStr = new Date(latestDate).toISOString();
console.log('dateStr=', dateStr);
//subtract a day
//ERROR OCCURS HERE, has trouble running // var subtractedDate = dateStr.setDate(('2020-11-17T00:00:00.000Z').getDate()-1);, something with how I have '2020-11-17T00:00:00.000Z' formatted?
var subtractedDate = dateStr.setDate(dateStr.getDate()-1);
console.log('subtractedDate = ', subtractedDate);
I am trying to use ('2020-11-17T00:00:00.000Z').getDate()-1 to subtract a day from the datetimestamp but it causes an error saying Uncaught TypeError: dateStr.getDate is not a function
We should be able to use Date.parse to get the number of milliseconds since January 1, 1970, 00:00:00 UTC, then subtract 1 days worth of milliseconds (246060*1000) to get the unix time one day earlier.
We can then use Date.toLocaleTimeString to format it.
const latestDate='2020-11-17';
// Get the number of milliseconds since 1970-1-1, then subtract 1 day (24*60*60*1000 milliseconds)
const dt = new Date(Date.parse(latestDate) - 24*60*60*1000);
// Format an ISO-8601 date in the UTC timezone
const subtractedDate = dt.toLocaleDateString('sv', { timeZone: 'UTC' });
console.log({ latestDate, subtractedDate })
Please try as follows.
dateStr.setDate(dateStr.getDate()-1);
var dateStr = new Date();
var month = dateStr.getUTCMonth() + 1; //months from 1-12
var day = dateStr.getUTCDate();
var year = dateStr.getUTCFullYear();
newdate = year + "/" + month + "/" + day;

Comparing two dates in JavaScript

I am currently trying to compare the launch_date with today's date. Let's say if the launch_date is within 3 years from today's date, it should perform something but I only managed to come out with some portion of the code:
var today = new Date();
var launch_date = 2011/10/17 00:00:00 UTC;
//if today's date minus launch_date is within 3 years, then do something.
Any guides? Thanks in advance.
To explicitly check for the three year range
var ld = new Date('2011/10/17 00:00:00 UTC')
if(today.getFullYear() - ld.getFullYear() < 3) {
//do something
}
This will fail on an invalid date string and possibly some other edge cases.
If you'll be doing a lot of date calculations I highly recommend Moment: http://momentjs.com/
you could always calculate the timespan in days and use that.
var getDays = function(startDate, endDate){
var ONE_DAY = 1000 * 60 * 60 * 24;
var difference = endDate.getTime() - startDate.getTime();
return Math.round(difference / ONE_DAY);
}
See this JsFiddle: http://jsfiddle.net/bj4Dq/1/
Try-
var today = new Date();
var launch_date = new Date("2011/10/17 00:00:00 UTC");
var diff = today.getYear() - launch_date.getYear();
if(diff <=3 )
alert("yes");
else
alert("no");
jsFiddle
you can create a Date object and invoke getTime() method (returns numer of milliseconds since 1970-01-01). Use one of this rows:
var yourDate = new Date(dateString) // format yyyy-mm-dd hh:mm:ss
var yourDate = new Date(year, month, day, hours, minutes, seconds, milliseconds)
After in the if statement use this condition:
var edgeDate = // new Date(dateString);
if ( (today.getTime () - yourDate.getTime ()) >= edgeDate.getTime() ){
// do something
}
Regards,
Kevin

Convert Returned String (YYYYMMDD) to Date

I have a string that contains 8 digits that represent a date. For example:
20120515
I'd like to compare it with today's date, created in this manner:
var currentDate = new Date();
How can I convert the "8 digit date string" to a suitable date format in order to compare it to currentDate?
Use the substring method and substring off 4 elements and assign it to your new date for the year. Then substring off two elements at a time and store the month and date accordingly.
var dateString = "20120515";
var year = dateString.substring(0,4);
var month = dateString.substring(4,6);
var day = dateString.substring(6,8);
var date = new Date(year, month-1, day);
var currentDate = new Date();
Now you can compare the two dates with the normal operators.
If you want a small date library you can use moment.js.
var a = moment("20120515", "YYYYMMDD");
// then use any of moment's manipulation or display functionality
a.format("MMM Do YYYY"); // May 15th 2012
a.fromNow(); // 14 hours ago
a.calendar(); // Today at 12:00 AM
To correctly handle the local time zone, it must explicitly summed to the calculated time
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
function dateStringToDate(dateString) {
try {
var year = dateString.substring(0, 4);
var month = dateString.substring(4, 6);
var day = dateString.substring(6, 8);
var date = new Date(year, month - 1, day);
const offset = date.getTimezoneOffset()
date = new Date(date.getTime() - (offset * 60 * 1000));
return date;
} catch (error) {
return null;
}
}
console.log(dateStringToDate("20211212"))
console.log(dateStringToDate("20211213"))
console.log(dateStringToDate("20211214"))
...some other "one-liner" ways to accomplish this:
(They take a value like dts='20020704'; and return date object [dt].)
var dt=new Date(dts.slice(0,4), (dts[4]+dts[5])-1, dts[6]+dts[7]);
...or...
var m=dts.match(/(....)(..)(..)/), dt=new Date(m[1],m[2]-1,m[3]);
...or...
var m=dts.match(/.{1,2}/g), dt=new Date(m[0]+m[1],m[2]-1,m[3]);
The last one's shortest, but the first is probably most efficient, since it doesn't use regex (but that's irrelevant, unless you're processing LOTS of data using this). I like the middle one best since it's easy to see what's happening.

Using answers from prompt for a calculation

Total newbie at JavaScript.
I would like to calculate how many days one has been alive by asking the user their date of birth via prompts/alerts, then obviously subtracting their date of birth from today's date.
I've made a bit of a start...
var month=prompt("Please enter month of birth"," ");
var day=prompt("Please enter day of birth"," ");
var year=prompt("Please enter your year of birth"," ");
var curdate = this is the bit i need help with
var birth = this is the bit i need help with
var milliDay = 1000 * 60 * 60 * 24; // a day in milliseconds;
var ageInDays = (curdate - birth) / milliDay;
document.write("You have been alive for: " + ageInDays);
Any advice or help would be much appreciated.
You need to use the Date object (MDN). They can be created from a month, a day, and a year, and added/subtracted.
Typically :
var curDate = new Date();
var birth = new Date(year, month, day);
var ageInDays = (curdate.getTime() - birth.getTime()) / milliDay;
Be aware of the fact that months starts at 0, e.g. January is 0.
var curDate = new Date();
gives you the current date.
var birthdate = new Date(year, month-1, day);
gives you a Date from the separate variables. NB the month is zero-based.
end = Date.now(); // Get current time in milliseconds from 1 Jan 1970
var date = 20; //Date you got from the user
var month = 8-1; // Month, subtracted by one because month starts from 0 according to JS
var year = 1996; // Year
//Set date to the old time
obj = new Date();
obj.setDate(date);
obj.setMonth(month);
obj.setYear(year);
obj = obj.getTime(); //Get old time in milliseconds from Jan 1 1970
document.write((end-obj)/(1000*60*60*24));
Simply subtract current time from Jan 1 1970 in milliseconds from their birthdate's time from Jan 1 1970 in milliseconds. Then convert it to days. Look at MDN's Docs for more info.
See JSFiddle for a working example. Try entering yesterday's date. It should show 1 day.
Read some of this: http://www.w3schools.com/js/js_obj_date.asp

Concatenate a date and time value

i need to concatenate a date value and a time value to make one value representing a datetime in javascript.
thanks,
daniel
Working with strings is fun and all, but let's suppose you have two datetimes and don't like relying on strings.
function combineDateWithTime(d, t)
{
return new Date(
d.getFullYear(),
d.getMonth(),
d.getDate(),
t.getHours(),
t.getMinutes(),
t.getSeconds(),
t.getMilliseconds()
);
}
Test:
var taxDay = new Date(2016, 3, 15); // months are 0-indexed but years and dates aren't.
var clockout = new Date(0001, 0, 1, 17);
var timeToDoTaxes = combineDateWithTime(taxDay, clockout);
// yields: Fri Apr 15 2016 17:00:00 GMT-0700 (Pacific Daylight Time)
I could not make the accepted answer work so used moment.js
date = moment(selected_date + ' ' + selected_time, "YYYY-MM-DD HH:mm");
date._i "11-06-2014 13:30"
Assuming "date" is the date string and "time" is the time string:
// create Date object from valid string inputs
var datetime = new Date(date+' '+time);
// format the output
var month = datetime.getMonth()+1;
var day = datetime.getDate();
var year = datetime.getFullYear();
var hour = this.getHours();
if (hour < 10)
hour = "0"+hour;
var min = this.getMinutes();
if (min < 10)
min = "0"+min;
var sec = this.getSeconds();
if (sec < 10)
sec = "0"+sec;
// put it all togeter
var dateTimeString = month+'/'+day+'/'+year+' '+hour+':'+min+':'+sec;
Depending on the type of the original date and time value there are some different ways to approach this.
A Date object (which has both date and time) may be created in a number of ways.
birthday = new Date("December 17, 1995 03:24:00");
birthday = new Date(1995,11,17);
birthday = new Date(1995,11,17,3,24,0);
If the original date and time also is objects of type Date, you may use getHours(), getMinutes(), and so on to extract the desired values.
For more information, see Mozilla Developer Center for the Date object.
If you provide more detailed information in your question I may edit the answer to be more specific.

Categories

Resources