Why does the date not adjust to the time set by UTC? - javascript

When printing the time for the clocks, a similar code works and adjusts for the timezone selected, but this does not work for printing the date. Any idea why?
It just displays the UTC default time.
<script>
function cetDT(){
var now = new Date();
var today = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var anHour = 1000 * 60 * 60;
today = new Date(today.getTime() - anHour * -2);
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
if (hours >= 12){
meridiem = "";
}
else {
meridiem = "";
}
if (minutes<10){
minutes = "0" + minutes;
}
else {
minutes = minutes;
}
if (seconds<10){
seconds = "0" + seconds;
}
else {
seconds = seconds;
}
document.getElementById("cetDT").innerHTML = (day + '/' + (parseFloat (month) + 1) + '/' + year);
}
cetDT();
</script>

You're using now.getUTCDate(), now.getUTCHours() and similar, which will grab the current date and time in UTC.
To get the local equivalent, you're looking for now.getDate(), now.getHours() etc. Note the lack of 'UTC' in the names.
Note that even though you're updating the today variable with today = new Date(today.getTime() - anHour * -2), today is initialed earlier with the UTC times. Thus, getTime() will be relative to UTC.
To resolve this, all you need to do is swap out the UTC times:
function cetDT() {
var now = new Date();
var today = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds());
var day = today.getDate();
var month = today.getMonth();
var year = today.getFullYear();
var anHour = 1000 * 60 * 60;
today = new Date(today.getTime() - anHour * -2);
var hours = today.getHours();
var minutes = today.getMinutes();
var seconds = today.getSeconds();
if (hours >= 12) {
meridiem = "";
} else {
meridiem = "";
}
if (minutes < 10) {
minutes = "0" + minutes;
} else {
minutes = minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
} else {
seconds = seconds;
}
document.getElementById("cetDT").innerHTML = (day + '/' + (parseFloat(month) + 1) + '/' + year);
}
cetDT();
Note that there's also several bits of code that are completely redundant, such as else { seconds = seconds; }. You may wish to look into refactoring this code ;)
Hope this helps! :)

Related

Remove seconds from a clock

I have been trying to do some research on how to do this but still no luck. Basically, I have a clock on a 12 hour format that shows automatically on page load. What I'm trying to do here is that how will I be able to change the clock format to 24 hour by using an AddEventLister? Would also like to add another AddEventListener that removes the seconds from it. Here's my code
function myClock() {
let date = new Date();
let hh = date.getHours();
let mm = date.getMinutes();
let ss = date.getSeconds();
let session = "AM";
if(hh == 0){
hh = 12;
}
if(hh > 12){
hh = hh - 12;
session = "PM";
}
hh = (hh < 10) ? "0" + hh : hh;
mm = (mm < 10) ? "0" + mm : mm;
ss = (ss < 10) ? "0" + ss : ss;
let time = hh + ":" + mm + ":" + ss + " " + session;
document.getElementById("time-now").innerText = time;
var t = setTimeout(function(){myClock()}, 1000);
}
myClock();
<span id="time-now"></span>
Here's the logic compressed (and edge-case tested) using .toLocaleTimeString(). With it, you can specify a locale and several formatting options, including 24-hour clock....
function myClock(locale) {
const date = new Date();
const time = date.toLocaleTimeString(locale, { hour12: false })
document.getElementById("time-now").innerText = time;
setTimeout(() => myClock(locale), 1000);
}
// US just for example
myClock('en-US');
<span id="time-now"></span>
const myClock=(locale)=> {
const date = new Date();
const time = date.toLocaleTimeString(locale, { hour12: false
})
document.getElementById("time-now").innerText = time;
setTimeout(() => myClock(locale), 1000);
}
// US just for example
myClock('en-US');

Add "am" or "pm" to Specific Time Format Dependent on Time of Day - Javascript

I have the following javaScript which is showing the time in hours and minutes.
Is there a way of having an "am" or "pm" next to the time, dependent on whether it's before or after midday?
var t = new Date();
var time = document.getElementById("time");
time.textContent = t.getHours() + ":" + t.getMinutes();
<h3 class="time-holder">Current UK time: <span id="time">12:00</span></h3>
Answer adapted from here.
var d = new Date();
var hr = d.getHours();
var min = d.getMinutes();
if (min < 10) {
min = "0" + min;
}
var ampm = "am";
if( hr > 12 ) {
hr -= 12;
ampm = "pm";
}
var time = document.getElementById("time");
time.textContent = hr + ":" + min + ampm;
<h3 class="time-holder">Current UK time: <span id="time">12:00</span></h3>
use the "toLocaleTimeString()" method instead of the "getHours()" and "getMinutes()"
for example:
var t = new Date();
var time = document.getElementById("time");
time.textContent = t.toLocaleTimeString('en-US');
source:
https://www.w3schools.com/jsref/jsref_tolocaletimestring.asp

How to convert UTC to CST using Javascript or Jquery

I would like to convert the below time to CST. How can I achieve it using Jquery or Javascript? It should always display as a CST timezone.
var date = new Date();
var dd = date.getDate();
var mm = date.getMonth() + 1;
var yy = date.getFullYear();
var hh = date.getHours();
var minutes = date.getMinutes();
if (minutes < 10)
minutes = "0" + minutes;
var suffix = "AM";
if (hh >= 12) {
suffix = "PM";
hh = hh - 12;
}
if (hh == 0) {
hh = 12;
}
if (dd < 10) {
dd = '0' + dd;
}
if (mm < 10) {
mm = '0' + mm;
}
var valsss = (mm) + "/" + dd + "/" + yy + hh + " " + ":" + minutes + " " + suffix;
$("#printDate").text(valsss);
<p id= "#printDate"></p>
Please check this below like can convert
d = new Date();
localTime = d.getTime();
localOffset = d.getTimezoneOffset() * 60000;
utc = localTime + localOffset;
offset = -5;
cst = utc + (3600000 * offset);
nd = new Date(cst);
newdate = (nd.toLocaleString());
$('#printDate').text(newdate + ' CST');
You have to consider that the browser will change the displayed date to the user's timezone. I wrote this to grab a date in a kendo grid by a class on a td and set it to CST. In this case the server is in CST and I wanted the time say 12:00 to display as 12:00 for a user in MST not as 11:00 in MST. Hope it helps...
Checks User / Browser's timezone offset.
Get difference in hours from server timezone offset.
Looks at a column on the Kendo Grid with class .dbDate.
Grabs the grid date (displayedTime).
Uses Moment.js to Convert (convertedTime) it based on the difference (diff)
in hours we pass it.
Formats convertedTime to the desired format i.e. 02/08/18 23:57.
Passes the Grid back the updated date and time.
Must Run Last on load.
function dateOffset() {
var date = new Date();
var offset;
var diff;
offset = date.getTimezoneOffset()
if (offset > 360) { //360 = CST
diff = +(offset - 360) / 60
} else if (offset < 360) {
diff = -(360 - offset) / 60
} else {
diff = 0
}
$(".dbDate").each(function (i) {
var grid = $('#Grid').data('kendoGrid');
var displayedTime = grid.dataSource.data()[i].TicketDateTime
var convertedTime = new moment(displayedTime).add(diff, 'hours').toDate();
var originalTime = moment(convertedTime).format("MM/DD/YY HH:mm");
i + 1
$(this).html(originalTime)
})
}

current time using javascript not grabbing correct location

Running a script to get current time for two specific locations. One time is for Mountain Time and the other is for East Coast Time. I am running into an issue where the Mountain Time clock is displaying time based on Pacific Standard Time if a user is based in a PST location. Rather than having PST is there a way for me to make sure that the two clocks are only getting MT and ET and taking into consideration daylight savings time as well?
$(document).ready(function(){
function timeDisplay() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if(hours >= 12){
hours = hours - 12;
meridiem = "pm";
}
else{
meridiem = "am";
}
if(hours === 0){
hours = 12;
}
if(hours < 10){
hours = "0" + hours;
}
if(minutes < 10){
minutes = "0" + minutes;
}
var clockDiv = document.getElementById('stat');
clockDiv.innerText = hours + ":" + minutes + meridiem;
}
timeDisplay();
setInterval(timeDisplay, 1000);
function newYorkTimeDisplay(offset) {
var currentTime = new Date();
currentTime.setHours(currentTime.getHours()+offset);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if(hours >= 12){
hours = hours - 12;
meridiem = "pm";
}
else{
meridiem = "am";
}
if(hours === 0){
hours = 12;
}
if(hours < 10){
hours = "0" + hours;
}
if(minutes < 10){
minutes = "0" + minutes;
}
var newYorkDiv = document.getElementById('newYork');
newYorkDiv.innerText = hours + ":" + minutes + meridiem;
}
newYorkTimeDisplay(+2);
setInterval(newYorkTimeDisplay, 1000, +2);
});
Any help on this is appreciated. Trying to figure out what I am missing.
Thanks in advance.
You need to get the user's current UTC timezone offset and subtract it from New York's Timezone Offset.
var tz_offset = (new Date().getTimezoneOffset()/100) - 3;
newYorkTimeDisplay(tz_offset);
$(document).ready(function() {
function timeDisplay() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if (hours >= 12) {
hours = hours - 12;
meridiem = "pm";
} else {
meridiem = "am";
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
var clockDiv = document.getElementById('stat');
clockDiv.innerText = hours + ":" + minutes + meridiem;
}
timeDisplay();
setInterval(timeDisplay, 1000);
function newYorkTimeDisplay(offset) {
var currentTime = new Date();
currentTime.setHours(currentTime.getHours() + offset);
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
//var seconds = currentTime.getSeconds();
var meridiem = " ";
if (hours >= 12) {
hours = hours - 12;
meridiem = "pm";
} else {
meridiem = "am";
}
if (hours === 0) {
hours = 12;
}
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
var newYorkDiv = document.getElementById('newYork');
newYorkDiv.innerText = hours + ":" + minutes + meridiem;
}
var tz_offset = (new Date().getTimezoneOffset()/100) - 3;
newYorkTimeDisplay(tz_offset);
setInterval(newYorkTimeDisplay, 1000, +2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=newYork></div>
<div id=stat></div>

Date and Time expiration logic not working

I am trying to check for a expired date and time logic. The time is in 12 hour clock format. I want to check if date is today, then user should not be able to pick expired time. However, if the date selected is tomorrow, then any time can be selected.If date is yesterady, then user should not be able to select the date.
I am trying to do a check in jquery, but not sure how to check. The date is in the format of "MM/DD/YYYY", and the time is in format of "hh:mm a". Expired time of 5 minutes is allowed. I have tried this code:
var targetTime = new Date().setMinutes(-5).valueOf();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth() + 1; //January is 0!
var yyyy = today.getFullYear();
if (dd < 10) {
dd = '0' + dd
}
if (mm < 10) {
mm = '0' + mm
}
today = mm + '/' + dd + '/' + yyyy;
if (jQuery('#startDatepicker').find("input").val() == today) {
var currentStartDate = jQuery('#startDatepicker').find("input").val();
var currentStartTime = jQuery('#startTimepicker').find("input").val();
var UserSelectedTime = getAsDate(currentStartDate, currentStartTime).getTime();
if (UserSelectedTime <= targetTime) {
alert("Start Time has expired. Please select a valid Start Time");
}
}
function getAsDate(day, time) {
var hours = Number(time.match(/^(\d+)/)[1]);
var minutes = Number(time.match(/:(\d+)/)[1]);
var AMPM = time.match(/\s(.*)$/)[1];
if (AMPM == "pm" && hours < 12) hours = hours + 12;
if (AMPM == "am" && hours == 12) hours = hours - 12;
var sHours = hours.toString();
var sMinutes = minutes.toString();
if (hours < 10) sHours = "0" + sHours;
if (minutes < 10) sMinutes = "0" + sMinutes;
time = sHours + ":" + sMinutes + ":00";
var d = new Date(day);
var n = d.toISOString().substring(0, 10);
var newDate = new Date(n + "T" + time);
return newDate;
}
If the current date is today and If the current time is 4:00 AM, if the user has selected 3:00 am , then the time has expired, but the alert message is not showing.
How to fix this?
Thanks

Categories

Resources