I have a Webhook listener that receives a unix timestamp value.
This timestamp is my END time.
I would like to use the current unix timestamp and compare what HH:MM:SS are left until the end time.
I was reading this post: How can i find HH:MM:SS difference between two UNIX timestamps?
and think it is very similar to my needs but needs a little tweaking.
Example:
Current time = unix now time
End time = unix time
= How many HH:MM:SS remain before the time has ended
I was trying;
function timeDiff(EpochTime) {
let msec = (new Date()).valueOf() - EpochTime * 1000;
const hh = Math.floor(msec / 1000 / 60 / 60);
msec -= hh * 1000 * 60 * 60;
const mm = Math.floor(msec / 1000 / 60);
msec -= mm * 1000 * 60;
const ss = Math.floor(msec / 1000);
msec -= ss * 1000;
return `${mm}m ${ss}s`;
}
Thanks
Magik
GNU awk is an option:
awk -v etim="2021 02 08 16 27 00" '{ print strftime("%c",mktime(etim)-strftime("%s"),1) }' <<< /dev/null
Pass the date/time as etim and the use GNU awk's strftime and mktime functions to print the difference in the passed date and now in the locale format. Change %c to what ever format is required.
Related
I am getting the elapsed time in minutes, hours and days, between two dates, a past date and the current one, I already get this data, but I want this data to change as the minutes, days and hours increase. For example, when I get to 60 minutes, the time changes to 1 hour and the minutes go to 0, when 24 hours go by, these hours change to a day and the hours go back to 0, and so on, the data I get keeps increasing , how can I do this?
const calculateDate = () => {
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const minutes= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / 60);
const hours= Math.floor((currentDate.getTime() - date.getTime()) / 1000 / (3600));
const days= Math.floor((currentDate.getTime() - date.getTime()) / (1000*60*60*24));
}
With this, get the minutes, hours and days, but how would you update so that when you reach 60 minutes it goes to one hour and 24 hours to one day?
The JavaScript Date object has built in functions for what you want to do.
var now = new Date()
var h = now.getHours()
var m = now.getMinutes()
var s = now.getSeconds()
The new Date created in above example is set to the time it was created.
You can get the current time using the Date object itself:
var current = Date()
With your method you always see the full duration just in a different unit.
You have to use the modulo operator to get only the "missing part" (the remainder of the division) to the next unit:
const date = new Date('Sun Sep 01 2022 01:32:06 GMT-0500');
const currentDate = new Date();
const dateDiff = (currentDate.getTime() - date.getTime()) / 1000;
const seconds = Math.floor(dateDiff) % 60;
const minutes = Math.floor(dateDiff / 60) % 60;
const hours = Math.floor(dateDiff / (60 * 60)) % 24;
const days = Math.floor(dateDiff / (60 * 60 * 24));
I want to convert HH:MM to MM I want to use minutes in below code but It can't convert 14:30 to 858 as you can see result here in fiddle minutes but it converts 14.3 to minutes if you put 14.3 in fiddle code instead of 14.30.
I am converting hrs. in minutes than I am Lessing 240 minutes from minutes I got How can I convert this hrs. in minute.
below is the code I am trying to convert hours to minutes
NOTE: hours can be can be any Time from 0 to 23 it could be 2:30 or it could be 10:30
function convertHourstoMinute(hours) {
return Math.floor(hours * 60);
}
let hrs = convertHourstoMinute(14:30); // convert hours into minutes javascript
console.log( "javascript convert hours to minutes :- " + hrs );
let minutes = hrs * 60;
console.log(minutes)
let callback_time = minutes - 240
console.log(callback_time)
let call_back = callback_time / 60
console.log(call_back)
A few things are incorrect in your code
first you can not pass 14:30 it has to be "14:30"
then 14:30 * 60 is not a valid expression it has to be 14 * 60 + 30
and you dont need Math.floor because you are not passing decimal numbers
if you want to pass decimal number then you have to use 14.5 instead 14:30
function convertH2M(timeInHour){
var timeParts = timeInHour.split(":");
return Number(timeParts[0]) * 60 + Number(timeParts[1]);
}
var timeInMinutes = convertH2M("14:30");
console.log(timeInMinutes);
If you want to pass decimal numbers instead of 14:30
then this example works
function convertH2M(timeInHour){
return Math.floor(timeInHour * 60);
}
var timeInMinutes = convertH2M(14.5);
console.log(timeInMinutes);
You need to pass variable type of string.
Then with ES6 magic which standardises destructuring assignment code could look like this and use + sign to convert string to Number:
function convertHourstoMinute(str) {
let [hours, minutes] = str.split(':');
return (+hours * 60) + (+minutes);
}
console.log( "javascript convert hours to minutes : ", convertHourstoMinute('14:30'));
You can try this to split the hour and minute and calculate then.
function convertHourstoMinute(time) {
var hour = time.split(':')[0]; //Split returns an array
var minute = time.split(':')[1];
return Math.floor(hour * 60) + pareseInt(minute);
}
You cannot use 14:30 in javascript, convert it to string first.
Try this
function convertHourstoMinute(time) {
var hour = time.split(':')[0]; //Split returns an array
var minute = time.split(':')[1];
return parseInt(hour) + Number((minute / 60));
}
let hrs = convertHourstoMinute("14:30"); // convert hours into minutes javascript
console.log( "javascript convert hours to minutes :- " + hrs );
let minutes = hrs * 60;
console.log(minutes)
let callback_time = minutes - 240
console.log(callback_time)
let call_back = callback_time / 60
console.log(call_back)
But to carry out further date manipulations I suggest you look into momentjs .
enter image description here
basically I insert a row with a datetime + interval (something in the future) with a SQL query.
$interval = new DateInterval('PT'.$H.'H'.$i.'M'.$s.'S');
$date = new DateTime(); $date->add($interval);
$query = $conn->prepare("INSERT INTO profiles_in_missions (id_pim, id_profile, id_mission, time) VALUES (NULL, :idprofile, :idmission,:time)");
$query->bindValue(':idprofile', $tableau[0]);
$query->bindValue(':idmission', $id);
$query->bindValue(':time', $date->format('Y-m-d H:i:s'));
$query->execute();
If my pc shows: 23:40, and if i insert DateTime with interval of +8minutes, this query will store 21:48 in the database. Till now okay, my database is GTM+00 and my pc default browser is GTM+2.
Once stored, i am trying to pick this date who got (in that case) -2h+8m and and make a countdown.
Now the problem: To make the countdown, i am using javascript and i do 21:48-now(); BUT he will always end 2h faster than normal, because the stored date (21:48) in MYSQL with GTM+00 BUT Javascript now(); is getting my default browser time GTM+2.
Is there a way to make Javascript work with server Timezone GTM+00? How can i fix my problem? There is all my code for the countdown:
<script>
var t = document.getElementById('myInputTimer').value;
var countDownDate = new Date(t).getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
new Date().getTime() (which can be replaced with Date.now()) simply returns the number of milliseconds from date zero. Timezone isn't a factor here, where timezone becomes a factor is here:
var t = document.getElementById('myInputTimer').value;
var countDownDate = new Date(t).getTime();
If the string you use to create the date object doesn't contain any timezone information, it assumes the timezone of the browser.
I'm assuming this string is the date you have in UTC time?
One solution is to make sure this string contains timezone information, which means it would look like this: 2017-06-03T22:23:00+00:00
Another solution is to correct for the timezone offset after you've parsed the date. So if new Date("2017-06-03 22:23:00") gives you Sat Jun 03 2017 22:23:00 GMT+0200 (CEST) which is 20:23 you can correct it by subtracting the timezone offset:
var countDownDate = new Date(t).getTime() - (new Date().getTimezoneOffset() * 60 * 1000);
.getTimezoneOffset() returns the timezone offset in minutes, we calculate how many milliseconds it is and then subtract it from the milliseconds returned by .getTime()
Using a string to create a date isn't the best idea however since it's implementation dependent and unreliable. It's better to parse out the various components (year, month, day, hours, and so on) and construct the date with those. You can use a regexp to parse out the components like this:
var dateParts = t.match(/\d+/g);
And the best part is that now you can use Date.UTC() instead of new Date(t).getTime() to get the time in UTC directly:
var countDownDate = Date.UTC.apply(null, dateParts);
I am getting a 16-digit Timestamp from the server.
For example : I got "1485157072432000" from the server and when I use the time stamp converter it is showing as Wed Oct 03 49032 04:43:52 GMT+0530 (India Standard Time)
However,I am getting the exact time when I remove the last 3-digits from the 16-digit number. But I'm getting 16 digit Timestamp from server. What is the way to get exact time from 16-digit Timestamp??
Since you need the microseconds precision I guess that the only solution is to use a custom object where you store all the information you need.
I would suggest you to use something like this utility developed by the GitHub user kamikane.
In particular you need the parse function that he developed:
function parse(nano) {
var ms = nano / 1000;
var ss = ms / 1000;
var mm = ss / 60;
var hh = mm / 60;
var dd = hh / 24;
var microseconds = Math.round((ms % 1) * 1000);
var milliseconds = Math.floor(ms % 1000);
var seconds = Math.floor(ss % 60);
var minutes = Math.floor(mm % 60);
var hours = Math.floor(hh % 24);
var days = Math.floor(dd);
return { microseconds: microseconds, milliseconds: milliseconds, seconds: seconds, minutes: minutes, hours: hours, days: days, toString: toString };
};
Example usage:
parse(1485157072432010);
{ microseconds: 10, milliseconds: 432, seconds: 52, minutes: 37, hours: 7, days: 17189 }
Is there a built in method in extjs or javascript for converting milliseconds to a time?
I found one for date, but it doesn't work. I always get Jan, 1 1970 08:00 (Pacific Standard Time). When I try test.getHours I get 0. I am trying to print out 8:00 or 08:00
var getSignOnRecord = 28800000;
var test = new Date(getSignOnRecord);
test.getHours() // 0 ???? Should be 8
you can use ISOString date formats for up to 24 hours of time:
new Date(28800000).toISOString().split("T")[1].split(".")[0]; // == "08:00:00"
you can easily slice() the remaining text to eliminate seconds or whatnot.
this works because using a "unix" stamp results in an GMT offset, and ISO also displays GMT, so by throwing away the date part, you're left with a pretty readable format of up to 23h59m59s...
You are getting the localized hour, but you want the hours at UTC
new Date(28800000).getUTCHours() // 8
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getHours
The getHours() method returns the hour for the specified date, according to local time.
new Date(value);
value: Integer value representing the number of milliseconds since 1 January 1970 00:00:00 UTC
28800000 ms is indeed 1 January 1970, 8h
When I try test.getHours I get 0
NB value is UTC, getHours is local time
This is a math problem. As far as I know, there is no function that does this in native JavaScript, but can be coded from scratch.
function convertToTime(milliseconds) {
var seconds = Math.floor(milliseconds / 1000) % 60
var minutes = Math.floor(milliseconds / (1000 * 60)) % 60
var hours = Math.floor(milliseconds / (1000 * 60 * 60)) % 24
return (hours < 10 ? "0" + hours : hours) + ":" +
(minutes < 10 ? "0" + minutes : minutes) + ":" +
(seconds < 10 ? "0" + seconds :seconds);
}
There's also probably a method like this in momentjs.