JavaScript: Parse time string and add minutes to it - javascript

$.getJSON("api/times", function(times) {
var time1 = times.departure; // 14:36:30 (string)
var minutesToAdd = parseInt(times.minutesToAdd); // 6
var total = "?"; // How can I add minutesToAdd to time1?
});
I am trying to parse time1 so that I can add the minutesToAdd value to the time. The time1 value comes directly from a MySQL database. It is obtained through an API that returns this data in JSON. How can I do this?

I think you can try this
on line 1 : You have to add a demo date with the time in javascript so that you can create the date object. Later you can do date.getTime() to get the time in milisecond.
var newDateObj = new Date("01/01/13 14:36:30"); // '01/01/13' is the demo value
alert(newDateObj)
var date = new Date(newDateObj.getTime() + 5*60000);
alert(date) // date.getTime() will give you the time

I you don't want to use Date, use split to get the three parts of your time string. Then you just add your minutes and make sure you don't exceed 59 minutes (if you think it is useful, check if hours doesn't exceed 23) :
$.getJSON("api/times", function(times) {
var time1 = times.departure; // 14:36:30 (string)
var minutesToAdd = parseInt(times.minutesToAdd);
var time = time1.split(':');
var time[1] += minutesToAdd;
if (time[1] >= 60) {
time[1] = 0;
time[0]++; // maybe you should test if >= 24
}
var total = time.join(':'); // equivalent to "time[0]+':'+time[1]+':'+time[2]"
});`

Related

Javascript - different timestamp values on the same client

Can someone please explain why these 3 different lines that suppose to produce the exact same result, give three different results?
The only accurate one is the 2'nd line (Date.now()). Unfortunately, this is the only one I can't use.
function show_ts_date(idx, ts)
{
var a = new Date(ts * 1000);
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
var year = a.getFullYear();
var month = months[a.getMonth()];
var date = a.getDate();
var hour = a.getHours();
var min = a.getMinutes();
var sec = a.getSeconds();
var formattedTime = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
alert(idx+'. timestamp: '+ts+' Date: '+formattedTime);
}
var currentdate = new Date();
//line 1: (produces wrong timestamp - it gives the wrong hour (-4) when I convert back to dateTime)
timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000);
show_ts_date(1, timestamp_1);
//line 2 (produces correct timastamp - it gives the correct hour when I convert back to DateTime.)
timestamp_2 = Math.floor(Date.now() / 1000);
show_ts_date(2, timestamp_2);
//line 3 (produces wrong timestamp - it gives the wrong hour (+3) when I convert back to dateTime)
let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
timestamp_4 = Math.floor( dat/ 1000);
show_ts_date(4, timestamp_4);
Well, assuming that Date.now() returns the real accurate value (I doubt it is always the case, But that's what I'm left with. you can always convert it back to Date and check if the right date & time came back),
I wrote this function that will compare between the right and wrong timestamps and will add (or decrease) the number of milliseconds from (or to) the false timestamp - turning it in to a correct one:
function getTimestampMilisecondsGap()
{
var currentdate = new Date();
timestamp_1 = Math.floor(new Date(currentdate.getFullYear()+'-'+(currentdate.getMonth()+1)+'-'+currentdate.getDate()+'T'+currentdate.getHours()+':'+currentdate.getMinutes()+':00') / 1000);
//let dat = new Date(Date.UTC(currentdate.getFullYear(), currentdate.getMonth(), currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), 00));
//timestamp_1 = Math.floor( dat/ 1000);
timestamp_2 = Math.floor(Date.now() / 1000); //this one is suppose to produce a correct timestamp
var addTimeStampMilisecs = 0;
if (timestamp_2 > timestamp_1)
{
addTimeStampMilisecs = timestamp_2-timestamp_1;
}
else if (timestamp_2 < timestamp_1)
{
addTimeStampMilisecs = timestamp_1-timestamp_2;
}
return addTimeStampMilisecs;
}
//writing a timestamp to the database
var destinationDateTimeStr = document.getElementById("dateyear").value+"-"+document.getElementById("datemonth").value+"-"+document.getElementById("dateday").value+"T"+document.getElementById("datehour").value+":"+document.getElementById("dateminute").value+":00";
var date2 = new Date(destinationDateTimeStr);
var eventDateTS = Math.floor(date2 / 1000); //convert to timestamp (with incorrect timezone)
eventDateTS += getTimestampMilisecondsGap(); //add (or decrese) the number of miliseconds from the timestamp because this function that generates the tmestamp returns a wrong number (the hour in the converted date is wrong)
//write the correct eventDateTS to your DB here...

How can I find the difference between two times [duplicate]

This question already has answers here:
Compare two dates with JavaScript
(44 answers)
How can I compare two time strings in the format HH:MM:SS?
(16 answers)
Closed 4 years ago.
How to find the difference between to times in JavaScript?
Here is the pseudocode I've come up with
var firstTime = "20:24:00";
var secondTime = "20:00:52";
console.log(firstTime - secondTime);// 23:08 (23 minutes, 8 seconds)
You could use new Date().setHours() to make to dates from the time you have and then subtract them, make a new date from the difference:
var firstTime = "20:24:00";
var secondTime = "20:00:52";
// transform variables into parameters
let dateA = new Date().setHours(...(firstTime.split(":")));
let dateB = new Date().setHours(...(secondTime.split(":")));
let diff = new Date(dateA-dateB);
console.log(`Differnce: ${diff.getUTCHours()}:${diff.getUTCMinutes()}:${diff.getUTCSeconds()}`);
Try this:
var myDate1 = new Date();
myDate1.setHours(20, 24, 00, 0);
var myDate2 = new Date();
myDate2.setHours(20, 00, 52, 0);
If you subtract them directly, it will give you a timestamp value. You can convert this value by saying:
var result = myDate1 - myDate2; // returns timestamp
var hours = new Date(result).getHours(); // returns hours
A while ago I had made a function similar to the one described:
let timeOp = function(operation, initial, value) {
// define the type of operation in bool if needed
if(typeof operation == "string") {
var operation = (operation == 'add') ? true : false;
}
// convert to minutes `value` if needded
if(!Number.isInteger(value)) {
var time = value.split(':');
value = parseInt(time[0]) * 60 + parseInt(time[1]);
}
// split the string and get the time in minutes
var time = initial.split(':');
time = parseInt(time[0]) * 60 + parseInt(time[1]);
// add or substract `value` to minute
time += (operation) ? value : -value;
// standardise minutes into hours
var hour = Math.floor(time / 60);
var minute = time % 60;
// return with '0' before if needed
return hour + ':' + ((minute>=10) ? minute : ('0' + minute))
}
let firstTime = "20:24";
let secondTime = "20:00";
console.log(timeOp('substract', firstTime, secondTime)
It's not perfect and it doesn't allow to use seconds. But you can figure that out pretty easily by modifying the above code.

Create date object and compare to todays date

I have an object containing time. For example x.time = 10:20:00.
I want to take the current time minus my objects time.
This is my code so far, but i get the error message ="Invalid Date":
for(var i = 0; i<x.length; i++){
nowDate = new Date();
minutesLeft = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + x[i].time);
text +- "It is "+ minutesLeft[i] + " milliseconds left";
}
In order to convert your time property into a date object you can do:
var timepieces = x.time.split(':');
var date = new Date();
date.setHours(timepieces[0]);
date.setMinutes(timepieces[1]);
date.setSeconds(timepieces[2]);
Then you can directly compare the two dates by using the getTime() method of the Date object.
nowDate.getTime() === date.getTime()
nowDate.getTime() > date.getTime()
nowDate.getTime() < date.getTime()
You can also get the difference of two dates in milliseconds:
var milliseconds = nowDate.getTime() - date.getTime();
There are a bunch of problems with your code. I'll go through and hopefully catch everything.
Use var to declare your variables inside your loop. (further reading)
When you create the variable minutesLeft you are doing a bit of weird concatenation. You told us that x.time is a string such as "10:20:00" but you are (string) concatenating that with Date.prototype.getDate which returns a number in the range 1-31 (representing the day of the month). You are essentially doing this:
minutesLeft = new Date(2017,0,1910:20:00);
Which I hope you see will not create a new date. You perhaps wanted something along the lines of
minutesLeft = new Date(2017,0,19, 10, 20, 0);
Which should give you what you want (todays date set to the appropriate time defined by x.time.
text +- does not make any sense. I suspect a typo, you meant text += which will append the value on the right to the variable text. Or, perhaps text = which will assign the value, replacing what was there
"It is "+ minutesLeft[i] + " milliseconds left" using minutesLeft[i] will take a single character from a string (or an item from an array, if the value is an array). Yours is just a date object, and is not an array, so I suspect you just meant to leave off the [i] part altogether.
If you're trying to get the difference between the current date/time and your selected date/time you need to do some arithmetic with nowDate and minutesLeft. I'm assuming this is a difference you're after.
var x = [{time:"10:20:20"}];
var text = "";
for(var i = 0; i<x.length; i++){
var nowDate = new Date();
var timeSplit = x[i].time.split(":");
var minutesLeft = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate());
minutesLeft.setHours(timeSplit[0]);
minutesLeft.setMinutes(timeSplit[1]);
minutesLeft.setSeconds(timeSplit[2]);
text += "It is "+ (nowDate-minutesLeft) + " milliseconds left";
}
console.log(text);
For example x.time = 10:20:00. I want to take the current time minus my objects time.
Your code seems quite confused, it seems you're trying to do the following:
var time = '10:20:00';
var timeParts = time.split(':');
var now = new Date();
// Current date and time
console.log(now.toString());
// Subtract the hours part of the time from the hours part of the current time
now.setHours(now.getHours() - timeParts[0]);
// Subtract the minutes part of the time from the minutes part of the current time
now.setMinutes(now.getMinutes() - timeParts[1]);
// Subtract the seconds part of the time from the seconds part of the current time
now.setSeconds(now.getSeconds() - timeParts[2]);
// Adjusted date and time
console.log(now.toString());
// You can set the time parts all in one go:
var now2 = new Date();
now2.setHours(now2.getHours() - timeParts[0],
now2.getMinutes() - timeParts[1],
now2.getSeconds() - timeParts[2]);
console.log(now2.toString());
Lastly, copying a date is as simple as:
var date1 = new Date();
var date2 = new Date(date1);

Convert thousands of seconds to h:mm:ss in moment.js

I've been going through the docs and I'm not sure what I'm doing wrong. I need to convert 7200 to 2:00:00. Seems easy? Some attempts:
var duration = 7200;
var display = moment().seconds(duration).format("h:mm:ss");
and...
var duration = 7200;
var display = moment.duration(duration, "seconds"); //can't chain on a format method?
The format comes back correct but the numbers are all wrong. If I use a duration of Math.round(7025.526) or 7025.526 I get 9:19:06 back.
How can I convert seconds to h:mm:ss successfully?
When you use moment().seconds(duration) it will take the current date and time, and then set the seconds component to the value (spilling over into minutes and hours). If you try it at different times you will see that the result changes.
A duration object can't be formatted as a date, because it's simply not a date. It's a length of time without any defined starting or ending point.
To convert the seconds first create an empty moment object, which will be the current date and the time 0:00:00. Then you can set the seconds, which will spill over into minutes and hours.
You would want to use H rather than h to format the hours. That avoids getting times less than an hour as 12:nn:nn instead of 0:nn:nn:
var duration = 7200;
var display = moment({}).seconds(duration).format("H:mm:ss");
let duration = seconds;
let hours = duration/3600;
duration = duration % (3600);
let min = parseInt(duration/60);
duration = duration % (60);
let sec = parseInt(duration);
if (sec < 10) {
sec = `0${sec}`;
}
if (min < 10) {
min = `0${min}`;
}
if (parseInt(hours, 10) > 0) {
return (`${parseInt(hours, 10)} : ${min} : ${sec}`)
}
return (`${min} : ${sec}`)
You can do it manually by calculating hours minutes and seconds
Using the moment-duration-format plugin:
var s = moment.duration(ms).format("h:mm:ss");
Or, just using moment:
var d = moment.duration(ms);
var s = Math.floor(d.asHours()) + moment.utc(ms).format(":mm:ss");

converting getTimezoneOffset() into static timezone

I have the problem of trying to convert a GMT timestamp on some json to localtime for use in Highcharts. But because there is a lag between getting the json with the timestamp and when the function runs to get the offset (and there may be more time since the timestamp on the json may not reflect the current time) my time is off a minute or two.
var dayLightSavings = true;
var lastMinute = "2013-05-16 22:09:00";
function convertDateTime(lastMinute){
var a = lastMinute.split(' ');
var d = a[0].split('-');
var t = a[1].split(':');
var epochGMT = Date.UTC(d[0],d[1]-1,d[2],t[0],t[1],t[2]);
var z = new Date();
if(dayLightSavings){ // IF TRUE ADD 60 minutes to clock
var n = z.getTimezoneOffset() + 60;
}else{
var n = z.getTimezoneOffset();
}
var epochLocal = epochGMT - (n * 60000);
return epochLocal;
}
How can I do this so that it gives me a range of numbers that equals a timezone that can be added or subtracted from the epochGMT time?
I was thinking something like a switch case:
switch(x){
case(x >= 0000 && x <= 0000):
epochLocal = epochGMT - 0000;
break;
case etc...
}

Categories