UTC time for css - javascript

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.

Related

How can I execute a condition using new Date in Javascript?

I have a curTime variable that is the current time using new Date() and a pwChangeDate value called from the backend data.
let curTime = new Date(); // Thu Oct 27 2022 15:02:34 GMT+0900
const pwDate = new Date(pwChangeDate) // Thu Oct 20 2022 13:51:57 GMT+0900
At this time, when pwDate passes 90 days based on curTime, I want to display an alert saying "90 days have passed." and when 83 days have passed, "7 days left out of 90 days." I want to display an alert.
but if i use my code it doesn't work how can i fix it?
const pwChangeDate = cookie.get('pwChangeDate');
const pwDate = new Date(pwChangeDate)
if (curTime.getDate() >= pwDate.getDate() - 90) {
alert('90 days have passed.')
}
if (curTime.getDate() >= pwDate.getDate() - 7) {
alert('7 days left out of 90 days..')
}
you can get the diff between current data and pwDate in days like this:
const pwDate = new Date('Thu Oct 20 2022 13:51:57 GMT+0900');
const diff = Math.floor((new Date - pwDate)/1000/60/60/24);
console.log(diff)
If you want to calcuate the days difference between pwDate and curTime, you can calculate like this.
Math.floor((pwDate.getTime() - curTime.getTime()) / (1000 * 60 * 60 * 24));
getTime() method returns a time value as milliseconds.
1000 * 60 * 60 * 24 is milliseconds per day.
OR
Using some library. (date-and-time)

How to rotate 360° day/night cycle image based on the real time of the day?

the day/night circle example:
https://i.ibb.co/fFskJ28/exmp.png
I want the day/night circle image (example in the link above) to rotate based on the real time (+1 UTC, no winter/summer time adjustments). The times you see in the image are already based on the +1 UTC time.
I already achieved to make this work in my game maker project, but now I also want this day/night circle image on my website so visitors can also see the day/night cycle live there.
I have already the working code written in GML, but now I want it in PHP/Javascript, and I know not much about Javascript, but I guess it is a must to use if I want the day/night cycle image to rotate in live time.
So here's my working code written in GML:
//written in GML
// unix_timestamp([datetime])
//
// Returns a Unix timestamp for the current time
// or optionally given GameMaker datetime value.
{
var timezone = date_get_timezone();
date_set_timezone(timezone_utc);
if (argument_count > 0) {
var datetime = argument[0];
} else {
var datetime = date_current_datetime();
}
var timestamp = round(date_second_span(25569, datetime));
date_set_timezone(timezone);
return timestamp;
}
The following part is a bit messy but does all what I want, making the variables 'hour' and 'minute' equal to the real time hour/minute in my country (+1 UTC)
//written in GML
rtime = unix_timestamp();
//removing all seconds from 1 jan 1970 00:00 - 1 jan 2019 00:00 (UTC+1 Amsterdam)
rtime2 = (rtime - 1546300800+3600);//the +3600 is meant to add 1 hour to
equalise to the UTC+1 time
//remove all remaining days
{
while (rtime2 >= 86400)
{
rtime2 -= 86400;
}
}
dtime = unix_timestamp();
//removing all seconds from 1 jan 1970 00:00 - 1 jan 2019 00:00 (UTC+1 Amsterdam)
dtime2 = (dtime - 1546300800+3600);//the +3600 is meant to add 1 hour to
equalise to the UTC+1 time
//number of days from 1 jan 2019 00:00
day_unf = (dtime2 / 86400);
day = (floor(day_unf) + 1);
//count all remaining hours
hour_unf = (rtime2 / 3600);
hour = (floor(hour_unf))
qtime = unix_timestamp();
//removing all seconds from 1 jan 1970 00:00 - 1 jan 2019 00:00 (UTC+1 Amsterdam)
qtime2 = (qtime - 1546300800+3600);//the +3600 is meant to add 1 hour to
equalise to the UTC+1 time
//remove all remaining days
{
while (qtime2 >= 86400)
{
qtime2 -= 86400;
}
}
removar = (hour * 60)
//count all remaining minutes
minute_unf = (qtime2 / 60);
minute_unf2 = (minute_unf - removar);
minute = (floor(minute_unf2))
xtime = unix_timestamp();
//removing all seconds from 1 jan 1970 00:00 - 1 jan 2019 00:00 (UTC+1 Amsterdam)
xtime2 = (xtime - 1546300800+3600);//the +3600 is meant to add 1 hour to
equalise to the UTC+1 time
//remove all remaining days
{
while (xtime2 >= 86400)
{
xtime2 -= 86400;
}
}
rem = (minute * 60);
rem2_unf = (hour * 3600);
xtime3 = (xtime2 - rem);
second = (xtime3 - rem2_unf);
if hour == 24{
hour = 0;
}
//written in GML
pre1 = 15 * hour;
pre2 = 0.25 * minute;
pre3 = pre1 + pre2;
cycle_angle = pre3;
//cycle_angle is always a number between 0-360 and is used below to draw the day/night circle image in the right rotation degree.
draw_sprite_ext(spr_day_night_cycle,0,960,80,image_xscale*1.5,image_yscale*1.5,cycle_angle,c_white,image_alpha);
Since the image is a circle of 360° degree, and it represents the time of one whole day of 24 hour, every passing hour is equal to 15° rotating, and every minute is equal to 0.25° rotating.
When the time is 18:30 for example, it rotates 277,5° (15 * 18 + 30 * 0.25) to represents that it is will day but the sunset is close.
So my questions are:
Question 1: How can I make the variables 'hour' and 'minute' in PHP/Javascript based on the real time hour/minute in my country (+1UTC, no winter/summer time adjustment needed)
Question 2: If I succeed in question 1, how can I rotate my day/night circle image on the website based on the 'hour' and 'minute' variables like I did in GML? (see GML example below)
//written in GML
pre1 = 15 * hour;
pre2 = 0.25 * minute;
pre3 = pre1 + pre2;
cycle_angle = pre3;
//cycle_angle is always a number between 0-360 and is used below to draw the day/night circle image in the right rotation degree.
draw_sprite_ext(spr_day_night_cycle,0,960,80,image_xscale*1.5,image_yscale*1.5,cycle_angle,c_white,image_alpha);
In PHP:
$date = new \DateTime();
$date->format('Y-m-d H:i:s'); //returns a string
There's many more functions in the DateTime object; read about it here
In JS:
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
You can then use those values and use CSS to rotate an image from 0-360 degrees using transform: rotate(360deg);

Javascript countdown and Timezones

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);

set javascript date object to before 30 days

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

Jquery time difference in hours from two fields

I have two fields in my form where users select an input time (start_time, end_time) I would like to, on the change of these fields, recalcuate the value for another field.
What I would like to do is get the amount of hours between 2 times. So for instance if I have a start_time of 5:30 and an end time of 7:50, I would like to put the result 2:33 into another field.
My inputted form times are in the format HH:MM:SS
So far I have tried...
$('#start_time,#end_time').on('change',function()
{
var start_time = $('#start_time').val();
var end_time = $('#end_time').val();
var diff = new Date(end_time) - new Date( start_time);
$('#setup_hours').val(diff);
try
var diff = ( new Date("1970-1-1 " + end_time) - new Date("1970-1-1 " + start_time) ) / 1000 / 60 / 60;
have a fiddle
It depends on what format you want your output in. When doing math with Date objects, it converts them into milliseconds since Epoch time (January 1, 1970, 00:00:00 UTC). By subtracting the two (and taking absolute value if you don't know which is greater) you get the raw number of milliseconds between the two.
From there, you can convert it into whatever format you want. To get the number of seconds, just divide that number by 1000. To get hours, minutes, and seconds:
var diff = Math.abs(new Date(end_time) - new Date(start_time));
var seconds = Math.floor(diff/1000); //ignore any left over units smaller than a second
var minutes = Math.floor(seconds/60);
seconds = seconds % 60;
var hours = Math.floor(minutes/60);
minutes = minutes % 60;
alert("Diff = " + hours + ":" + minutes + ":" + seconds);
You could of course make this smarter with some conditionals, but this is just to show you that using math you can format it in whatever form you want. Just keep in mind that a Date object always has a date, not just a time, so you can store this in a Date object but if it is greater than 24 hours you will end up with information not really representing a "distance" between the two.
var start = '5:30';
var end = '7:50';
s = start.split(':');
e = end.split(':');
min = e[1]-s[1];
hour_carry = 0;
if(min < 0){
min += 60;
hour_carry += 1;
}
hour = e[0]-s[0]-hour_carry;
min = ((min/60)*100).toString()
diff = hour + ":" + min.substring(0,2);
alert(diff);
try this :
var diff = new Date("Aug 08 2012 9:30") - new Date("Aug 08 2012 5:30");
diff_time = diff/(60*60*1000);

Categories