Javascript / Jquery - Calculate date and time - javascript

Given
departing date time 13/6/2014 01:00 AM
and
estimated landing time is 1 hour 50 minutes
i want the result like: 13/6/2014 2:50 AM
anyone have idea?
i have been using datejs with no luck

Here, take a look at moment.js (http://momentjs.com)
So let's say you have your starting time and duration set up like this:
var departTime = '13/06/2014 01:00 AM';
var duration = '1 hour 50 minutes';
First you need to convert the depart time to a moment object and parse the duration, like so:
var departTimeObj = moment(departTime, 'MM/DD/YYYY hh:mm A');
var durationParts = duration.split(' ');
var durationHours = durationParts[0];
var durationMinutes = durationParts[2];
Now you can use moment to do the addition:
var landingTime = departTimeObj.add({
hours: durationHours,
minutes: durationMinutes
});
To format the output the way you want, do this:
var landingTimeStr = landingTime.format('MM/DD/YYYY hh:mm A');

Use the JavaScript date object.
var travelling = 110 // in minutes
var departing = new Date(2014, 6, 13, 1, 0, 0, 0);
var arriving = new Date(departing.getTime() + travelling * 60000);
Here's a fiddle.
Or use many of the libraries already out there.
As Matt Johnson says, you need to be weary of gotchas like daylight saving time if you're going to be adding variable units of time like days.

Related

Getting same unix time stamp for two different times in javascript

I had two ical format timestamps and I want to convert them to normal time first and then to unix time.
Here this is the function I've been using to convert normal time to unix timestamp:
var normal_to_unix = function (date_string) {
var date = new Date(date_string);
return date.getTime() / 1000;
}
This function is fine since date is already in UTC and I need not do any conversions.
Now this is the function I've been using to convert ical time to unix time. The ical time in my case is like "20180603T150000Z".
var ics_to_unix = function (ics_string) {
var year = ics_string.slice(0, 4);
var month = ics_string.slice(4, 6);
var date = ics_string.slice(6, 8);
var hours = ics_string.slice(9, 11);
var minutes = ics_string.slice(11, 13);
var seconds = ics_string.slice(13, 15);
var milliseconds = 0;
console.log(year, month, date, hours, minutes, seconds, milliseconds); // This is example output 2018 06 03 15 00 00 0
return normal_to_unix((new Date(year, month, date, hours, minutes, seconds, milliseconds)).toDateString())
}
Now the problem is I'm getting the same unix time for "20180603T150000Z" and "20180603T160000Z" which are supposed to give different timestamps and it is 1530576000 for both of them.
Is there anything that I'm missing ? Thanks in advance.
Please have a look at this for live example
Several points here:
The toDateString() method returns the date portion of a Date object in human readable form in American English. For your example it is `Tue Jul 03 2018', perhaps that is not what you want.
new Date creates date in your local timezone, which could play well if you use it together with toString(), which will also return the string for date in your local timezone. But it will be subject to daylight saving changes, so I'd avoid using that method.
Another thing I'd like to avoid converting back and forth between strings and dates, since it does a lot of unnecessary computations.
I'd suggest to use the following:
var ics_to_unix = function (ics_string) {
var year = parseInt(ics_string.slice(0, 4));
var month = parseInt(ics_string.slice(4, 6)) - 1; // Jan is 0
var date = parseInt(ics_string.slice(6, 8));
var hours = parseInt(ics_string.slice(9, 11));
var minutes = parseInt(ics_string.slice(11, 13));
var seconds = parseInt(ics_string.slice(13, 15));
return Date.UTC(year, month, date, hours, minutes, seconds) / 1000;
}
I have added explicit conversion of strings to numbers, adjusted the month to match what is used in javascript and also removed the extra call.

How do I calculate the number of days between a particular date in the future and today?

This is what I have tried. Am getting 21 which is definitely not right. What am I doing wrong?
var today = new Date();
var TrumpsStateVisit = new Date('March 12, 2018 12:00:00');
var daysTillTrumpsStateVisit = TrumpsStateVisit.getTime() - today.getTime();
daysTillTrumpsStateVisit = (daysTillTrumpsStateVisit / 864000000); //number of milleseconds in a day
var $countDownTillTrumpsChinaTrip = ('#countDownTillTrumpsChinaTrip');
$countDownTillTrumpsChinaTrip.textContent = Math.floor(daysTillTrumpsStateVisit);
The main reason this doesn't work is that the number of milliseconds in a day is 100*60*60*24=86400000. You also should construct the date differently as that will be March 12, 2018 12:00 in whatever timezone the users browsers in which might not be what you intend.
However there a number of settle issues related to time changes and other issues when subtracting dates so you should really use a library like https://momentjs.com/ that specializes in handling dates and times.
You were so close!
The main problem is that there aren't 864000000 milliseconds in a day, there are only 86400000; you had one zero too many.
A secondary problem occurs with Daylight Savings; not every day has exactly 24 hours in it, so you need to round the result rather than floor it:
var today = new Date();
var TrumpsStateVisit = new Date('March 12, 2018 12:00:00');
var daysTillTrumpsStateVisit = TrumpsStateVisit.getTime() - today.getTime();
daysTillTrumpsStateVisit = (daysTillTrumpsStateVisit / 86400000); //number of milleseconds in a day
console.log(Math.round(daysTillTrumpsStateVisit));
Hope this helps! :)

Only want to compare TIME values MomentJS

After looking through some of the other MomentJS Questions and answers I'm still stumped as to how one would use moment to simply compare two different times.
I do not need (want) the day/date to be considered.
My use case is this:
I'm reading a schedule (start/end times) from a config file. This is done using Node.js
Starttime = 6:30 PM
Endtime = 3:30 AM
var currentTime= moment(); // e.g. 11:00 pm
var starttime = moment('06:30 pm', "HH:mm a");
var endtime = moment('03:30 am', "HH:mm a");
amIBetween = currtime.isBetween(starttime , endtime);
console.log(amIBetween); // returns false
My scenario is technically spanning two days and I understand why it's false.
I need (expect) moment to return TRUE - i.e. that currtime isBeteen start and endtime and falls in that range.
Would I need to check for a time after 12AM and then add a day to make the check work?
Any other suggestions for accomplishing this. I looked at moment-range which has 'contains ' function but with similar question for that.
I'm finding it hard to believe that it's this complex, but maybe it is :\
--
Here's further clarification that issue arises with spanning days, even when trying to be more explicit:
var currentTime= moment('11:00p', "HH:mm a");
var startTime = moment('06:00p', "HH:mm a");
var endTime = moment('03:30a', "HH:mm a");
currentTime.toString(); //"Fri Oct 28 2016 23:00:00 GMT-0400"
startTime.toString(); // "Fri Oct 28 2016 18:00:00 GMT-0400"
endTime.toString(); // "Fri Oct 28 2016 03:30:00 GMT-0400"
currentTime.isBetween(startTime, endTime); // false
currentTime.isAfter(endTime) && currentTime.isBefore(startTime); //false
currentTime.isAfter(startTime) && currentTime.isBefore(endTime); //false
Seems kind of obvious that they'd be false since the day/date is considered by moment. This is what I'm trying to get around.
The following would work:
endTime.add(1, "days");
currentTime.isBetween(startTime, endTime); // TRUE
This would mean however, that I'd need to check if the START TIME was before 12AM && the ENDTIME as after 12AM then add 1 day to ENDTIME. Kludge?
After my own testing and looking at other's suggestions it sill appeared that disregarding DAY/DATE and trying to span days was an issue. I came up with this which is now working in my app.
isTimeBetween = function(aStartTime, anEndTime, aCurrTime)
{
// you may pass in aCurrTime or use the *actual* current time
var currentTime = !aCurrTime ? moment() : moment(aCurrTime, "HH:mm a");
var startTime = moment(aStartTime, "HH:mm a");
var endTime = moment(anEndTime, "HH:mm a");
if (startTime.hour() >=12 && endTime.hour() <=12 )
{
endTime.add(1, "days"); // handle spanning days
}
var isBetween = currentTime.isBetween(startTime, endTime);
/*** testing
startTimeString = startTime.toString();
endTimeString = endTime.toString();
currentTimeString = currentTime.toString();
console.log(startTimeString);
console.log(endTimeString);
console.log(currentTimeString);
console.log('\nis '+ currentTimeString + ' between ' +
startTimeString + ' and ' + endTimeString + ' : '
+ isBetween);
****/
return isBetween;
}
isTimeBetween("06:30pm", "03:30am", "11:00pm"); //true !! this is main use case
isTimeBetween("06:30pm", "10:30pm", "11:00pm"); //false
isTimeBetween("04:00am", "06:00am"); //true (e.g. current time is 5am
I see two issues.
1) Your variable name currtime on line 5 is different than your declaration on line 1 currentTime
2) You could break it up into two checks around midnight like so:
var currentTime = moment(); // e.g. 11:00 pm
var sixThirty = moment('06:30 pm', "HH:mm a");
var midnight = moment('12:00 am', "HH:mm a");
var threeThirty = moment('03:30 am', "HH:mm a");
amIBetween1 = currentTime.isBetween(sixThirty , midnight);
amIBetween2 = currentTime.isBetween(midnight , threeThirty);
console.log(amIBetween1);
console.log(amIBetween2);
dylpickle's answer looks correct to me, but if you decide that the isBetween is easy to fumble, then you may want to take that abstraction away, take a step down into it's functionality.
"explicitness is far cheaper than the wrong abstraction"
That is not to say that isBetween is the wrong abstraction, but it is a tiny bit less explicit in that you could easily feed it the parameters in the wrong answer which would give you the opposite of what you intended.
If you
console.log(currentTime.isBetween)
you get the implementation:
ob(a,b,c,d){return d=d||"()",("("===d[0]?this.isAfter(a,c):!this.isBefore(a,c))&&(")"===d[1]?this.isBefore(b,c):!this.isAfter(b,c))}
Notice that it just uses isAfter() and isBefore().
Sometimes you can simplify things sometimes by being more explicit with your code.
isBetween looks a little uglified and seems to cover all of the edge cases, but don't be afraid to try to improve things either.
Try the following code:
const isBetween = currentTime.isAfter(endtime) && currentTime.isBefore(starttime);
console.log(isBetween)
There is no way to get confused in the implementation or adding changes later. This does not increase cyclomatic complexity or lines of code.
I was facing the same issue and I did a kind of work around as follows:
function fgEsHora1MayorAHora2(hora1, hora2) {
var f1 = moment('2000-01-01 ' + hora1);
f1.tz('America/Mexico_City').format('ha z');
let f1Hora = f1.toObject().hours;
let f1Minutos = f1.toObject().minutes;
var f2 = moment('2000-01-01 ' + hora2);
f2.tz('America/Mexico_City').format('ha z');
let f2Hora = f2.toObject().hours;
let f2Minutos = f2.toObject().minutes;
let minutos1 = parseInt(f1Hora * 100) + parseInt(f1Minutos);
let minutos2 = parseInt(f2Hora * 100) + parseInt(f2Minutos);
return minutos1 > minutos2;
}
I separated the hours and multiply it by 100 in order to give it more value... so, I added "hours" plus minutes and then I did the comparison..
Remarks: The trick stands on add the date like "2001-01-01", just to be able to get the time and hour...
And it's working fine!!

how to add time plus and recalculate the datetime

i have this datetime format:
Oct 31, 2012 08:59:52
i would like to re-calculate the datetime incremented (for example) of 2 hours or 50 minutes plus how can i do that?
i need to return the same datetime format showed above and not a timestamp!
var date = new Date("Oct 31, 2012 08:59:52");
var timeInMillis = date.getTime();
Now that you have time in milliseconds, you can just add the time you want in millis.
Eg: 2 hours? So, 2*60*60*1000 + timeInMillis
var newDate = new Date(2*60*60*1000 + timeInMillis);
If you want to convert your newDate into the original format, which is a long process, you can some guidance from here:
Where can I find documentation on formatting a date in JavaScript?
My pick of the answers would be:
Use MomentJS
You could first parse this to a date:
var d=new Date("October 31, 2012 08:59:25").getTime();
Then add the offset:
d+= (seconds)*1000 + (minutes)*60000 + (hours)*3600000;
var result = new Date(d);
I am just not sure wether it accepts 'Oct' instead of 'October'
time_start = new Date(year, month, day, hours, minutes, seconds, milliseconds);
time_finish = new Date() - time_start;
Set the Date using the format listed above. To calculate the interval between two points of time, just subtract the current date from the past date.

how to format time with jquery/javascript

I have a JSON feed that drupal spits out time in this format: 2010-12-16T04:41:35Z
How do I go about formating it to X minutes/hours ago?
Take a look at the timeago jQuery plugin which can be used programtically like
var t = jQuery.timeago("2010-12-16T04:41:35Z");
or on HTML elements like
<time class="timeago" datetime="2008-07-17T09:24:17Z">July 17, 2008</time>
<script type="javascript">
jQuery(document).ready(function() {
jQuery("time.timeago").timeago();
});
</script>
I think something on this page will help you. There's a couple formatting jQuery plugins toward the bottom. Good luck!
Here is a highly relevant Stack Overflow post: How can I convert string to datetime with format specification in JavaScript?
You can use regexp object in JS to build your own regular expression, separate hours-minutes-secs from the original string and then do whatever you want.
Tip: actual_date - your original string time
does the 04:41:35 part is correct? or do you need like to take into consideration time zones and stuff?
because basically this can work:
var str = "2010-12-16T04:41:35Z"
var arr = str.split("T")
arr[0] = arr[0].split("-")
arr[1] = (arr[1].replace(/Z/ig,"")).split(":")
var year = arr[0][0]
var month = parseInt(arr[0][1],10)-1
var day = arr[0][2]
var hours = arr[1][0]
var minutes = arr[1][1]
var seconds = arr[1][2]
var d = new Date(year, month, day, hours, minutes, seconds, 0);
var now = (new Date())
var diffMS = now.getTime() - d.getTime()
//alert ("difference in milliseconds: " + diffMS)
var hoursago = diffMS/1000/60
var ANDminutes = (diffMS - Math.floor(hoursago) * 1000*60)/1000
alert (Math.floor(hoursago) + " hours and " + ANDminutes + " minutes ago")
<shameless_plug>
Here's a library which give you a humanized time difference.
https://github.com/layam/js_humanized_time_span
The output is completely customizable, allowing you to set different output formats for various time bands; So you could have:
'10 seconds ago'
or
'3 days and 2 hours ago'
you can even set custom time units.
Additionally it's native JS and so doesn't rely on any framework.
</shameless_plug>

Categories

Resources