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);
Related
I have a problem I cant wrap my head around. The Date string is acting different in two instances where I think I am doing the same thing.
SO in essence, when I assign new Date("Jan 25, 2023 15:37:25").getTime() to countDownDate, the timer here (controlled by setInterval), will start where I expect it based on the string literal that is input into the date constructor. This will persist to count even on refresh.
The problem is when I need to calculate a future time dynamically. ALl of a sudden, when I calculate a dynamic future time string:
var timer = new Date().getTime() + 620840000;
var date = new Date(timer);
var dateStr = date.toString();
var countDownDate new Date(dateStr).getTime()
this no longer persists on refresh.
Now I am aware that in general you need to store the time in localstorage or even a server to allow the time to persist. which makes sense. I also understand that the timer is being recalculated every time the component is mounted. However, arent I doing the same exact thing by putting a static string literal into the date constructor? If its a matter of setting and resetting, shouldnt the date constructor with the string literal act the same way as a dynamically calculated string? pull
code here: https://github.com/Cerezze/timerTest
import logo from './logo.svg';
import './App.css';
import { useEffect } from 'react';
function App() {
useEffect(() => {
var timer = new Date().getTime() + 620840000;
var date = new Date(timer);
var dateStr = date.toString();
var countDownDate = new Date("Jan 25, 2023 15:37:25").getTime(); // <-- Why does this persist on refresh
/*var countDownDate new Date(dateStr).getTime();*/ // <-- and this does not persist on refresh?
const interval = setInterval(() => {
var now = new Date().getTime();
var distance = countDownDate - now;
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
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);
console.log(days, hours, minutes, seconds);
}, 1000);
return (distance) => {
if(distance < 0){
clearInterval(interval);
console.log('Expired');
}
}
}, []);
return (
<div className="App">
</div>
);
}
export default App;
If I understand your question, then the answer is that here
var timer = new Date().getTime() + 620840000;
you are creating a different date/time every time your javascript runs (new Date() will always be the present time according to the system clock)
var date = new Date(timer);
var dateStr = date.toString();
but here, you have a fixed date/time, which stays the same each time.
var countDownDate = new Date("Jan 25, 2023 15:37:25").getTime(); // <-- Why does this persist on refresh
Does that answer your question? I would have put this in a comment, but I wanted to show you in your code where I think your misunderstanding is
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'm trying to get a difference between two dates in seconds. The logic would be like this :
set an initial date which would be now;
set a final date which would be the initial date plus some amount of seconds in future ( let's say 15 for instance )
get the difference between those two ( the amount of seconds )
The reason why I'm doing it it with dates it's because the final date / time depends on some other variables and it's never the same ( it depends on how fast a user does something ) and I also store the initial date for other things.
I've been trying something like this :
var _initial = new Date(),
_initial = _initial.setDate(_initial.getDate()),
_final = new Date(_initial);
_final = _final.setDate(_final.getDate() + 15 / 1000 * 60);
var dif = Math.round((_final - _initial) / (1000 * 60));
The thing is that I never get the right difference. I tried dividing by 24 * 60 which would leave me with the seconds, but I never get it right. So what is it wrong with my logic ? I might be making some stupid mistake as it's quite late, but it bothers me that I cannot get it to work :)
The Code
var startDate = new Date();
// Do your operations
var endDate = new Date();
var seconds = (endDate.getTime() - startDate.getTime()) / 1000;
Or even simpler (endDate - startDate) / 1000 as pointed out in the comments unless you're using typescript.
The explanation
You need to call the getTime() method for the Date objects, and then simply subtract them and divide by 1000 (since it's originally in milliseconds). As an extra, when you're calling the getDate() method, you're in fact getting the day of the month as an integer between 1 and 31 (not zero based) as opposed to the epoch time you'd get from calling the getTime() method, representing the number of milliseconds since January 1st 1970, 00:00
Rant
Depending on what your date related operations are, you might want to invest in integrating a library such as day.js or Luxon which make things so much easier for the developer, but that's just a matter of personal preference.
For example in Luxon we would do t1.diff(t2, "seconds") which is beautiful.
Useful docs for this answer
Why 1970?
Date object
Date's getTime method
Date's getDate method
Need more accuracy than just seconds?
You can use new Date().getTime() for getting timestamps. Then you can calculate the difference between end and start and finally transform the timestamp which is ms into s.
const start = new Date().getTime();
const end = new Date().getTime();
const diff = end - start;
const seconds = Math.floor(diff / 1000 % 60);
Below code will give the time difference in second.
import Foundation
var date1 = new Date(); // current date
var date2 = new Date("06/26/2018"); // mm/dd/yyyy format
var timeDiff = Math.abs(date2.getTime() - date1.getTime()); // in miliseconds
var timeDiffInSecond = Math.ceil(timeDiff / 1000); // in second
alert(timeDiffInSecond );
<script type="text/javascript">
var _initial = '2015-05-21T10:17:28.593Z';
var fromTime = new Date(_initial);
var toTime = new Date();
var differenceTravel = toTime.getTime() - fromTime.getTime();
var seconds = Math.floor((differenceTravel) / (1000));
document.write('+ seconds +');
</script>
Accurate and fast will give output in seconds:
let startDate = new Date()
let endDate = new Date("yyyy-MM-dd'T'HH:mm:ssZ");
let seconds = Math.round((endDate.getTime() - startDate.getTime()) / 1000);
time difference between now and 10 minutes later using momentjs
let start_time = moment().format('YYYY-MM-DD HH:mm:ss');
let next_time = moment().add(10, 'm').format('YYYY-MM-DD HH:mm:ss');
let diff_milliseconds = Date.parse(next_time) - Date.parse(star_time);
let diff_seconds = diff_milliseconds * 1000;
let startTime = new Date(timeStamp1);
let endTime = new Date(timeStamp2);
to get the difference between the dates in seconds ->
let timeDiffInSeconds = Math.floor((endTime - startTime) / 1000);
but this porduces results in utc(for some reason that i dont know).
So you have to take account for timezone offset, which you can do so by adding
new Date().getTimezoneOffset();
but this gives timezone offset in minutes, so you have to multiply it by 60 to get the difference in seconds.
let timeDiffInSecondsWithTZOffset = timeDiffInSeconds + (new Date().getTimezoneOffset() * 60);
This will produce result which is correct according to any timezone & wont add/subtract hours based on your timezone relative to utc.
Define two dates using new Date().
Calculate the time difference of two dates using date2. getTime() – date1. getTime();
Calculate the no. of days between two dates, divide the time difference of both the dates by no. of milliseconds in a day (10006060*24)
const getTimeBetweenDates = (startDate, endDate) => {
const seconds = Math.floor((endDate - startDate) / 1000);
const minutes = Math.floor(seconds / 60);
const hours = Math.floor(minutes / 60);
const days = Math.floor(hours / 24);
return { seconds, minutes, hours, days };
};
try using dedicated functions from high level programming languages. JavaScript .getSeconds(); suits here:
var specifiedTime = new Date("November 02, 2017 06:00:00");
var specifiedTimeSeconds = specifiedTime.getSeconds();
var currentTime = new Date();
var currentTimeSeconds = currentTime.getSeconds();
alert(specifiedTimeSeconds-currentTimeSeconds);
Lets say now the date is 10/07/2015, ie If I create a javascript date object like as shown below I will get todays date as 07/10/2015
var now = new Date();
So if the date is 10/07/2015 I want 30 days back date i.e 07/09/2015.
I did like as shown below but for that I got 31/08/2015
var now = new Date();
now .setDate(-30);
Can anyone please tell me some solution for this
You can try like this:
Date.today().add(-30).days();
And if you want then moment.js is really good when dealing with dates
moment().subtract(30, 'days');
And if you dont want to use any library then
var now = new Date()
var prev = new Date().setDate(now.getDate()-30)
You could have simply use now.getDate():
var now = new Date();
document.write(now);
now.setDate(now.getDate() - 30);
document.write("<br/>");
document.write(now);
A Date object internally contains a value that corresponds to the number of milliseconds passed since 1 January, 1970 UTC.
As such, using this value (accessible via Date.prototype.valueOf()) you can add or subtract any size of "simply calculated" time interval. By simply calculated I mean anything that can be calculated using simple arithmetics, such as (for example..) "1 day 4 hours and 2 minutes" is equal to (((1 * 24) + 4) * 60 + 2) * 60 * 1000. You can add / subtract that to any starting time and create a new Date object:
var startDate = new Date();
var newDate = new Date(startDate.valueOf() + ((((1 * 24) + 4) * 60 + 2) * 60 * 1000));
alert(newDate);
In the specific case of days offset, simply use this formula:
days * 24 * 60 * 60 * 1000
I have this script working it gives me the UTC time but it goes over 24!
example
sydney time 13 + (-11) = 2 | Los Angeles time 19 +(7) = 26
this 26 show be 2! because 24 is maximum
var now = new Date();
var utc = (now.getHours() + (now.getTimezoneOffset() / 60));
Use
now.getUTCHours()
For reference see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getUTCHours
You don't need to, and shouldn't, calculate this. getUTCHours gets you UTC time.
That said, if you still want to do the calculation / make your life harder:
var now = new Date();
var utc = (now.getHours() + (now.getTimezoneOffset() / 60)) % 24;
The % 24 is necessary to account for situations (like you encountered) where the conversion yields a number outside 0-23.