I'm working on a script which would create a countdown timer based on string date and time that the admin defines. I have it already coded, however, there is a problem of users seeing different timers depending on their timezone. For instance, if the admin set the date and time to today, 4:50 PM (an hour from now), he'd see the timer at 01:00:00, while I'd see it at 04:00:00. Obviously, I'd like the timer to display the same for everyone.
Any ideas?
Here's part of the code:
//stringDate is the date and time string the admin sets
var splitSD = stringDate.split(' ');
//isolate date, time, notation
var splitDate = splitSD[0];
var splitTime = splitSD[1];
var splitNotation = splitSD[2];
//isolate month, day, year
var formatDate = splitDate.split('/');
formatDate['month'] = formatDate[0];
formatDate['day'] = formatDate[1];
formatDate['year'] = formatDate[2];
//isolate hour, minute, second
var formatTime = splitTime.split(':');
formatTime['hour'] = formatTime[0];
formatTime['minute'] = formatTime[1];
formatTime['second'] = '00';
//change hour to 24-hour clock based on notation
if(splitNotation == 'PM' && parseInt(formatTime['hour'])<12){
formatTime['hour'] = parseInt(formatTime['hour']) + 12;
}
if(splitNotation == 'AM' && parseInt(formatTime['hour'])==12){
formatTime['hour'] = parseInt(formatTime['hour']) - 12;
}
//prepend 0 in case...
formatDate['month'] = (formatDate['month'].length == 1) ? '0'+formatDate['month'] : formatDate['month'];
formatDate['day'] = (formatDate['day'].length == 1) ? '0'+formatDate['day'] : formatDate['day'];
formatTime['hour'] = (formatTime['hour'].length == 1) ? '0'+formatTime['hour'] : formatTime['hour'];
formatTime['minute'] = (formatTime['minute'].length == 1) ? '0'+formatTime['minute'] : formatTime['minute'];
//format full date and prevent conversion to local time
var fullFD = new Date(formatDate['year'] + '-' + formatDate['month'] + '-' + formatDate['day'] + 'T' + formatTime['hour'] + ':' + formatTime['minute'] + ':00-08:00');
//make timestamp
var fullFDTimestamp = Math.round(fullFD / 1000);
return fullFDTimestamp;
Answer-ing my comment, as requested.
Use Date.prototype's getTimezoneOffset method. It gives the difference, in minutes, between the local time and GMT UTC. You can calibrate the countdown timer to take into account this offset value and show the desired time.
Related
I'm struggling to compare two times.
I need to print Current class going based on the current time.
Example: current time based class going on the college/school
var now = new Date();
var TwentyFourHour = now.getHours();
var hour = now.getHours();
var min = now.getMinutes();
var mid = 'PM';
if (min < 10) {
min = "0" + min;
}
if (hour > 12) {
hour = hour - 12;
}
if (hour == 0) {
hour = 12;
}
if (TwentyFourHour < 12) {
mid = 'AM';
}
Current_time = hour + ':' + min + ':' + mid;
start_time = "09:00:PM";
end_time = "10:00:PM";
if (parseInt(start_time) <= parseInt(Current_time) || parseInt(end_time) >= parseInt(Current_time)) {
console.log("C programming class is going");
} else {
console.log("No class are avalible");
}
OUTPUT:
C programming class is going....
It seems you are looking for the shortest path to have your homework done.
Please check the references for Date function:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date
Some tips:
Make sure you understand how the Date object is created. You can use strings!
If you want to define date manually using each day, month , value, you can!
Check your strings.. are you sure "09:00:PM" is a valid string for date?
Are you sure you can use parseInt for parsing dates?
Anyway, you need to do more research.
The easiest way to check if a time is between a start and an end time is to store the time using unix time(https://en.wikipedia.org/wiki/Unix_time). It represents the time in seconds after 00:00:00 UTC on 1 January 1970. so you can do the following:
const startTime = 1624802400 // 27.6.21 16:00
const endTime = 1624809600 //27.6.21 18:00
const currentTime = Date.now()/1000
if(currentTime < endTime && currentTime > startTime){
console.log('Class is going')
}
if(currentTime > endTime){
console.log('Class ended')
}
if(currentTime < startTime){
console.log('Class has not started')
}
Date.now() returns the current time in milliseconds so you need to divide it by 1000
I have wordpress website where I am creating events with time to it.
I can access it using following in my php function file.
$start_date = DateTime::createFromFormat( AGENDA_SESSION_DATE_RETURN_FORMAT, $session['start_date'] );
$start_date = strtoupper( $start_date->format( 'g:i a' ) );
$end_date = DateTime::createFromFormat( AGENDA_SESSION_DATE_RETURN_FORMAT, $session['end_date'] );
$end_date = strtoupper( $end_date->format( 'g:i a' ) );
It uses server time and I want to convert it into Visitor local time + PST time.
I have following server time stored into database.
I want to convert it into following.
I don't want make it using visitor's IP address.
Instead I want to use visitor's OS Time which can be accessed using into JavaScript.
I can pass PHP date into JavaScript.
Is there any way to do this ?
Requirement: display the times in the user's timezone instead of the server's timezone.
Anyone can help me into this ??
Thanks
Try following steps
Step 1 : Add PHP Server date timestamp to the html data field of your template.
<span class="soap_time_custom"
data-starttime="<?php echo strtotime(get_field( 'start_date_time', $post_id )); ?>"
data-endtime="<?php echo strtotime(get_field( 'end_date_time', $post_id )); ?>" ></span>
Step 2 : Calculate difference of your server time with visitor's local time. Code sample below.
Step 3 : For timezone use moment.js from here.
$(document).ready(function() {
var timedelay = setTimeout(function(){
if($(".soap_time_custom").length>0)
{
$(".soap_time_custom").each(function(index, element) {
var starttime = $(this).data("starttime"); // 2020-10-18 18:00:00 / 1603044000
var endtime = $(this).data("endtime"); // 2020-10-18 18:10:00
if(starttime !== "" && endtime != ""){
var d = new Date();
var n = d.getTimezoneOffset();
var ClientSide_starttime = new Date((parseFloat(starttime)+n+350)*1000);
var ClientSide_endtime = new Date((parseFloat(endtime)+n+350)*1000);
//var local_time_zone = (new Date()).toTimeString().match(new RegExp("[A-Z](?!.*[\(])","g")).join('');
var local_time_zone = moment.tz(Intl.DateTimeFormat().resolvedOptions().timeZone).zoneAbbr();
var new_local_time = formatAMPM(ClientSide_starttime)+" / "+formatAMPM(ClientSide_endtime)+" "+local_time_zone.toUpperCase();
$(this).html(new_local_time+" — ");
}
});
}
}, 2500,'');
function formatAMPM(date) {
var hours = date.getHours();
var minutes = date.getMinutes();
var ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12; // the hour '0' should be '12'
minutes = minutes < 10 ? '0'+minutes : minutes;
var strTime = hours + ':' + minutes + ' ' + ampm;
return strTime;
}
});
Note : For timezone you will have to use 2 files momentjs and timezone extension as shown in screenshot above.
I modified the code below to create a time string which looks exactly the way I want it. It is how my Timex watch displays time.
Is there a native way to do this? I feel like I must have re-invented the wheel as surely many have needed this method before me.
const api = {};
// gets a time string which is human readable using the Date object
api.getTime = function() {
const date = new Date();
// get minutes and add a 0 if needed
let min = date.getMinutes();
min = (parseInt(min, 10) < 10 ? '0' : '') + min;
// get hours, determine AM or PM and change to 12 hours
// not preceding 0 is needed
let hour = date.getHours();
const amPm = hour >= 12 ? 'PM' : 'AM';
hour = ( hour % 12 ) || 12;
// get seconds and add a 0 if needed
let sec = date.getSeconds();
sec = (parseInt(sec, 10) < 10 ? '0' : '') + sec;
return `${hour}:${min}:${sec} ${amPm}`;
}
module.exports = api;
I think it is definitely helping if you take a look at toLocaleTimeString(), from the documentation:
Return the time portion of a Date object as a string, using locale conventions.
You can test out this function as the following:
const date = new Date().toLocaleTimeString();
console.log(date);
I hope that helps!
So i have a json object, which returned me basically a datetime object, now the question, what is the most efficient way of formatting this to a single string human readable format, in the users (client) local timezone... In javascript
created: {
timezone: {
name: "America/New_York",
location: {
country_code: "US",
latitude: 40.71417,
longitude: -74.00639,
comments: "Eastern Time"
}
},
offset: -18000,
timestamp: 1454125056
},
If the timestamp is an ECMAScript time value (i.e. milliseconds since 1970-01-01T00:00:00Z) then you can give that value directly to a Date object:
var d = new Date(1454125056); // 1970-01-17T19:55:25.056Z
however it is more likely seconds, so multiply by 1,000:
new Date(1454125056*1000).toISOString(); // 2016-01-30T03:37:36.000Z
which will create a Date for that moment in time. The offset should probably be ignored, unless it was used in the creation of the time value, in which case it should be added if it follows the ISO convention of negative for west and positive for east. If it follows the ECMAScript convention, the opposite applies.
I'll assume ISO, and since it appears to be seconds, you can apply it to the UTC seconds:
var offset = -18000;
d.setUTCSeconds(d.getUTCSeconds() + offset);
console.log(d.toISOString()); // 2016-01-29T22:37:36.000Z
Using plain Date methods thereafter will return values based on the host system's timezone settings.
var timeValue = 1454125056;
var offset = -18000;
var d = new Date(timeValue*1000);
document.write(d.toISOString() + '<br>' + d);
d.setUTCSeconds(d.getUTCSeconds() + offset);
document.write('<br>' + d.toISOString() + '<br>' + d);
There are many questions here on how to format a date string from a Date object.
Note that javascript is only required consider the daylight saving rules in force at the current time as if they had always existed, so be careful with historical dates.
Suppose this json object loaded in $created variable. i assume you mean php.
in PHP :
$obj = json_decode($created, true);
$timezone_name = $obj['timezone']['name'];
$timezone_location_country_code = $obj['timezone']['location']['country_code'];
$timezone_location_latitude = $obj['timezone']['location']['latitude'];
$timezone_location_longitude = $obj['timezone']['location']['longitude'];
$timezone_location_comments = $obj['timezone']['location']['comments'];
$offset = $obj['offset'];
$timestamp = date('m/d/Y', abs($obj['timestamp']));
in Javascript :
getDate: function(timestamp){
// Multiply by 1000 because JS works in milliseconds instead of the UNIX seconds
var date = new Date(timestamp * 1000);
var year = date.getUTCFullYear();
var month = date.getUTCMonth() + 1; // getMonth() is zero-indexed, so we’ll increment to get the correct month number
var day = date.getUTCDate();
var hours = date.getUTCHours();
var minutes = date.getUTCMinutes();
var seconds = date.getUTCSeconds();
month = (month < 10) ? ‘0’ + month : month;
day = (day < 10) ? ‘0’ + day : day;
hours = (hours < 10) ? ‘0’ + hours : hours;
minutes = (minutes < 10) ? ‘0’ + minutes : minutes;
seconds = (seconds < 10) ? ‘0’ + seconds: seconds;
return year + ‘-‘ + month + ‘-‘ + day + ‘ ‘ + hours + ‘:’ + minutes;
}
I get a variable string like so:
8:45 am
And want, if it is pm, to convert it to 24 hour time. So that I can then drop the am/pm and use it with something else.
I can drop the am/pm quite easily like this:
function replaceEnds(string) {
string = string.replace("am", "");
string = string.replace("pm", "");
return string;
}
But of course if I do that, I don't know if the string is am or pm, so I don't know to add 12 hours on to the string to make it 24 hour.
Anyone know how I could resolve this? I absolutely cannot change the input that I get of the variable, it'll always be the hour (in 12 hour time), minutes, and am or pm.
Using moment.js:
moment(string, 'h:mm a').format('H:mm');
If you want to do it manually, this would be my solution:
function to24Hour(str) {
var tokens = /([10]?\d):([0-5]\d) ([ap]m)/i.exec(str);
if (tokens == null) { return null; }
if (tokens[3].toLowerCase() === 'pm' && tokens[1] !== '12') {
tokens[1] = '' + (12 + (+tokens[1]));
} else if (tokens[3].toLowerCase() === 'am' && tokens[1] === '12') {
tokens[1] = '00';
}
return tokens[1] + ':' + tokens[2];
}
The manual solution is harder to understand, is less flexible, is missing some error checking and needs unit tests. In general, you should usually prefer a well-tested popular library's solution, rather than your own (if a well-tested library is available).
Without using any additional JavaScript libraries:
/**
* #var amPmString - Time component (e.g. "8:45 PM")
* #returns - 24 hour time string
*/
function getTwentyFourHourTime(amPmString) {
var d = new Date("1/1/2013 " + amPmString);
return d.getHours() + ':' + d.getMinutes();
}
So for example:
getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"
In case you're looking for a solution that converts ANY FORMAT to 24 hours HH:MM correctly.
function get24hTime(str){
str = String(str).toLowerCase().replace(/\s/g, '');
var has_am = str.indexOf('am') >= 0;
var has_pm = str.indexOf('pm') >= 0;
// first strip off the am/pm, leave it either hour or hour:minute
str = str.replace('am', '').replace('pm', '');
// if hour, convert to hour:00
if (str.indexOf(':') < 0) str = str + ':00';
// now it's hour:minute
// we add am/pm back if striped out before
if (has_am) str += ' am';
if (has_pm) str += ' pm';
// now its either hour:minute, or hour:minute am/pm
// put it in a date object, it will convert to 24 hours format for us
var d = new Date("1/1/2011 " + str);
// make hours and minutes double digits
var doubleDigits = function(n){
return (parseInt(n) < 10) ? "0" + n : String(n);
};
return doubleDigits(d.getHours()) + ':' + doubleDigits(d.getMinutes());
}
console.log(get24hTime('6')); // 06:00
console.log(get24hTime('6am')); // 06:00
console.log(get24hTime('6pm')); // 18:00
console.log(get24hTime('6:11pm')); // 18:11
console.log(get24hTime('6:11')); // 06:11
console.log(get24hTime('18')); // 18:00
console.log(get24hTime('18:11')); // 18:11
I've use something similar to this
//time is an array of [hh] & [mm am/pm] (you can get this by time = time.split(":");
function MilitaryTime(time){
if(time[1].indexOf("AM")!=-1){
//its in the morning, so leave as is
return time;
}else if(time[0]!="12"){
//If it is beyond 12 o clock in the after noon, add twelve for military time.
time[0]=String(parseInt(time[0])+12);
return time;
}
else{
return time;
}
}
Once you get your time returned, you can alter the text in any way you want.