How to get UTC timezone in javascript and adjust to PDT/PT - javascript

I have a countdown timer timer constructed but it's just using getTime(), i'm unsure how to adjust this so it is the correct timezone i want (PDT/PT)
var countdownTimer = setInterval(countdownTick, 1000);
function countdownTick() {
jQuery('ul.countdown').each(function() {
var date = jQuery(this).attr('data-date').split('-'); // Create date array from attribute
var time = jQuery(this).attr('data-time').split('-'); // Create time array from attribute
for (var i = 0; i < date.length; i++) {
date[i] = parseInt(date[i]);
}
for (var i = 0; i < time.length; i++) {
time[i] = parseInt(time[i]);
}
var today = new Date();
var theDate = new Date(date[0], (date[1] - 1), date[2], time[0], time[1]);
if (theDate.getTime() > today.getTime()) { // If the target date is in the future
countdownCalc(this, theDate, today); // Calculate how much time there is until the target date
}
});
}
function countdownCalc(obj, targetDate, currentDate) {
var oneDay = 1000 * 60 * 60 * 24;
var oneSecond = 1000;
var output = (targetDate.getTime() - currentDate.getTime());
var day = Math.floor(output / oneDay);
var hour = Math.floor((output - (day * oneDay)) / (1000 * 60 * 60));
var minute = Math.floor((output - (hour * (1000 * 60 * 60) + (day * oneDay))) / (1000 * 60));
var second = Math.floor((output - ((minute * 60000) + (hour * 1000 * 60 * 60) + (day * oneDay))) / 1000);
jQuery(obj).html('<li><span class="countdown-label">DAYS</span><span class="countdown-number">' + day + '</span></li><li><span class="countdown-label">HOURS</span><span class="countdown-number">' + hour + '</span></li><li><span class="countdown-label">MINUTES</span><span class="countdown-number">' + minute + '</span></li><li><span class="countdown-label">SECONDS</span><span class="countdown-number">' + second + '</span></li>');
}
https://jsfiddle.net/4nag4h5v/

Here is where plugins become useful, using moment-timezone.js
We are able to do something is simple as:
let time = Date.now();
moment(time).tz("YOURTIMEZONE").format('x') // get timestamp (in milliseconds

Without using an external library, the simplest way to do it is by using an offset between your local and target timezones:
let today = new Date(),
localOffset = -(today.getTimezoneOffset()/60),
targetOffset = -8,
netOffset = targetOffset - targetOffset;
const d = new Date(new Date().getTime() + netOffset * 3600 * 1000);

Related

Javascript Countdown Variable

I am trying to get the date to change to second date. On the first date, I would like it to show Starts: in bold and then the remaining time. I have it figured to change to a second date. When it changes to the second date, i want it to show Ends: in bold then the remaining time. When both countdown timers end, I want it to display text saying the event has ended. Here is what I have so far.
<script>
// Set the date we're counting down to
var countDownDate = new Date("July 23, 2020 21:07:00").getTime();
var countDownDate2 = new Date("July 23, 2020 21:08:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
var distance2 = countDownDate2 - now;
var a;
if (distance < 0 && distance2 >0) {
a = distance2;
} else {
a = distance;
}
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(a / (1000 * 60 * 60 * 24));
var hours = Math.floor((a % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((a % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((a % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = "Starts: " + days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// Change to another exp.
if (distance < 0 && distance2 >0) {
function changeDate() {
a = distance2;
}
}
// If the count down is over, write some text
if (distance2 < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}}, 1000);
</script>
It seems you basically have it figured out, if I'm understanding the question. You just need another variable for the Start/End label, and then use it when you set .innerHTML of the demo element.
<div id="demo"></div>
<script>
// Set the date we're counting down to
//var countDownDate = new Date("July 23, 2020 21:07:00").getTime();
var countDownDate = Date.now() + 5000; // using a shorter time for testing purposes;
// var countDownDate2 = new Date("July 23, 2020 21:08:00").getTime();
var countDownDate2 = Date.now() + 10000;
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
var distance2 = countDownDate2 - now;
var a;
var label = 'Starts: ';
if (distance < 0 && distance2 >0) {
a = distance2;
label = 'Ends: ';
} else {
a = distance;
}
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(a / (1000 * 60 * 60 * 24));
var hours = Math.floor((a % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((a % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((a % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = "<strong>" + label + "</strong>" + days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// Change to another exp.
if (distance < 0 && distance2 >0) {
function changeDate() {
a = distance2;
}
}
// If the count down is over, write some text
if (distance2 < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}}, 1000);
</script>

Lost trying to create a stopwatch

I'm trying to self-taugh JavaScript and while doing some texts with a stopwatch I got lost into this problem. It's working but it's always starting on 95:34:47 instead of 00:00:00
This is what i tried so far.
<script>
/*Timer Stuff*/
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
var d = new Date();
var n = d.getTime();
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
MyVar = setInterval(update, 1);
}
</script>
</head>
<body>
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
</body>
I understand that I need to subtract an specific amount of time to match the timer accurately, however I can't figure out how to do it.
You need to store a variable with the start time, and subtract from that. The 95 you're getting for the hours is actually much higher, just being cropped, being that you're calculating from the Unix epoch.
I would just do it something like this:
function update() {
var d = new Date();
var n = d - startTime;
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
startTime = new Date();
MyVar = setInterval(update, 1);
}
Note that you don't even need to use d.getTime() when subtracting -- you can just subtract Date objects themselves.
You have to introduce a start-time variable.
In every update-step you have to get the difference from start to now.
For your code:
<script>
/*Timer Stuff*/
timestart = new Date();
timestart_time = timestart.getTime();
function pad(num, size) {
var s = "0000" + num;
return s.substr(s.length - size);
}
function formatTime(time) {
time = time -timestart_time;
var h = m = s = ms = 0;
var newTime = '';
h = Math.floor( time / (60 * 60 * 1000) );
time = time % (60 * 60 * 1000);
m = Math.floor( time / (60 * 1000) );
time = time % (60 * 1000);
s = Math.floor( time / 1000 );
ms = time % 1000;
newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 3);
return newTime;
}
function update() {
var d = new Date();
var n = d.getTime();
document.getElementById("time").innerHTML = formatTime(n);
}
function start() {
MyVar = setInterval(update, 1);
}
</script>
</head>
<body>
<div>Time: <span id="time"></span></div>
<input type="button" value="start" onclick="start();">
</body>
That works for me :)

How to calculate the different between two datepickers

im trying to calculate the date different for a two datepicker in JavaScript. I tried following other posts, but everytime i calculate the date diff * price, but i'm not getting a result. Can someone please direct me into the right direction in order to accomplish my goal in finding date differential between two datepickers.
//input/saving data for the next form
$(".next").click(function(){
start = $('#checkin').val();
ends = $('#checkout').val();
diff = (ends - start);
days = diff/1000/60/60/24;
//roomPrice = price inserted into selection type(Single = 65, Double = 100, Suite = 120)
roomPrice = Rprices[selectType.value];
//preparing form5
fields = [$('#FirstName').val() + ' ' + $('#LastName').val(),
$('#phone').val(),
$('#email').val(),
$('#StreetAddress').val(),
$('#City').val(),
$('#state').val(),
$('#zip').val(),
$('#checkin').val(),
$('#checkout').val(),
$('#RoomType').val(),
$('#NumOfPeople').val(),
document.getElementById("total").value = days * roomPrice];
I'm not sure what you are asking but:
start = $('#checkin').val(); // assuming this is a date
ends = $('#checkout').val(); // assuming this is a date
var start_date = new Date(start); // assuming the format is correct
var end_date = new Date(ends); // assuming the format is correct
var diff_ms = end_date.getTime() - start_date.getTime(); // assuming both dates exist
will get you the time difference in milliseconds.
getDateDiff(time1, time2) {
var t2 = new Date(time1);
var t1 = new Date(time2);
var diffMS = t1 - t2;
var ret = "";
ret = ret + parseInt(diffMS / 1000 / 60 / 60).toString() + " hours ";
diffMS = diffMS - parseInt(diffMS / 1000 / 60 / 60) * 60 * 60 * 1000;
ret = ret + parseInt(diffMS / 1000 / 60).toString() + " min ";
diffMS = diffMS - parseInt(diffMS / 1000 / 60) * 60 * 1000;
ret = ret + parseInt(diffMS / 1000).toString() + " sec";
return ret ;
}

calculate time difference between two date in HH:MM:SS javascript

I have created one timer application in javascript.
Firstly it takes the current UTC date to init timer with some reference. here's the code
on_timer: function(e) {
var self = this;
if ($(e.target).hasClass("pt_timer_start")) {
var current_date = this.get_current_UTCDate();
this.project_timesheet_db.set_current_timer_activity({date: current_date});
this.start_interval();
this.initialize_timer();
this.$el.find(".pt_timer_start,.pt_timer_stop").toggleClass("o_hidden");
Now, Once timer is started and after some time span timer has some elapsed time with reference to above on_timer: function(e) function.
This function is
start_interval: function() {
var timer_activity = this.project_timesheet_db.get_current_timer_activity();
var self = this;
this.intervalTimer = setInterval(function(){
self.$el.find(".pt_duration").each(function() {
var el_hour = $(this).find("span.hours");
var el_minute = $(this).find("span.minutes");
var minute = parseInt(el_minute.text());
if(minute >= 60) {
el_hour.text(_.str.sprintf("%02d", parseInt(el_hour.text()) + 1));
minute = 0;
}
el_minute.text(_.str.sprintf("%02d", minute));
var el_second = $(this).find("span.seconds");
var seconds = parseInt(el_second.text()) + 1;
if(seconds > 60) {
el_minute.text(_.str.sprintf("%02d", parseInt(el_minute.text()) + 1));
seconds = 0;
}
el_second.text(_.str.sprintf("%02d", seconds));
});
}, 1000);
},
Now, considering el_hour, el_minute, el_seconds How to can i count time difference between init time and current timer value in HH:MM:SS manner.
thanks in advance for help
To convert H:M:S to seconds, you can use a simple function like:
// Convert H:M:S to seconds
// Seconds are optional (i.e. n:n is treated as h:s)
function hmsToSeconds(s) {
var b = s.split(':');
return b[0]*3600 + b[1]*60 + (+b[2] || 0);
}
Then to convert seconds back to HMS:
// Convert seconds to hh:mm:ss
// Allow for -ve time values
function secondsToHMS(secs) {
function z(n){return (n<10?'0':'') + n;}
var sign = secs < 0? '-':'';
secs = Math.abs(secs);
return sign + z(secs/3600 |0) + ':' + z((secs%3600) / 60 |0) + ':' + z(secs%60);
}
var a = '01:43:28';
var b = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(a) - hmsToSeconds(b))); // -10:39:18
console.log(secondsToHMS(hmsToSeconds(b) - hmsToSeconds(a))); // 10:39:18
You may want to abbreviate the function names to say:
toHMS(toSec(a) - toSec(b)); // -10:39:18
Note that this doesn't cover where the time may cross a daylight saving boundary. For that you need fully qualified dates that include the year, month and day. Use the values to create date objects, find the difference, convert to seconds and use the secondsToHMS function.
Edit
The question title mentions dates, however the content only seems to mention strings of hours, minutes and seconds.
If you have Date objects, you can get the difference between them in milliseconds using:
var diffMilliseconds = date0 - date1;
and convert to seconds:
var diffSeconds = diffMilliseconds / 1000;
and present as HH:MM:SS using the secondsToHMS function above:
secondsToHMS((date0 - date1) / 1000);
e.g.
var d0 = new Date(2014,10,10,1,43,28);
var d1 = new Date(2014,10,10,12,22,46);
console.log( secondsToHMS((d0 - d1) / 1000)); // -10:39:18
I think there is a simpler solution.
function dateDiffToString(a, b){
// make checks to make sure a and b are not null
// and that they are date | integers types
diff = Math.abs(a - b);
ms = diff % 1000;
diff = (diff - ms) / 1000
ss = diff % 60;
diff = (diff - ss) / 60
mm = diff % 60;
diff = (diff - mm) / 60
hh = diff % 24;
days = (diff - hh) / 24
return days + ":" + hh+":"+mm+":"+ss+"."+ms;
}
var today = new Date()
var yest = new Date()
yest = yest.setDate(today.getDate()-1)
console.log(dateDiffToString(yest, today))
const dateDiffToString = (a, b) => {
let diff = Math.abs(a - b);
let ms = diff % 1000;
diff = (diff - ms) / 1000;
let s = diff % 60;
diff = (diff - s) / 60;
let m = diff % 60;
diff = (diff - m) / 60;
let h = diff;
let ss = s <= 9 && s >= 0 ? `0${s}` : s;
let mm = m <= 9 && m >= 0 ? `0${m}` : m;
let hh = h <= 9 && h >= 0 ? `0${h}` : h;
return hh + ':' + mm + ':' + ss;
};
This may be the simple answer
var d1 = new Date(2014,10,11,1,43,28);
var d2 = new Date(2014,10,11,2,53,58);
var date = new Date(d2-d1);
var hour = date.getUTCHours();
var min = date.getUTCMinutes();
var sec = date.getUTCSeconds();
var day = date.getUTCDate() - 1;
console.log(day + ":" + hour + ":" + min + ":" + sec)
More intuitive and easier to read.
function hmsToSeconds(t) {
const [hours, minutes, seconds] = t.split(':')
return Number(hours) * 60 * 60 + Number(minutes) * 60 + Number(seconds)
}
function secondsToHMS(secs) {
return new Date(secs * 1000).toISOString().substr(11, 8)
}
var startTime = '01:43:28';
var endTime = '12:22:46';
console.log(secondsToHMS(hmsToSeconds(endTime) - hmsToSeconds(startTime))); //10:39:18

getting trouble in calculating time difference

this is my javascript code to calculate time difference:
var startTime = '11:30 am';
var EndTime = '1:30 pm';
var ed = EndTime.split(':');
var st = startTime.split(':');
var sub = parseInt(ed[0]) * 60 + parseInt(ed[1]);
var sub1 = parseInt(st[0]) * 60 + parseInt(st[1]);
i am getting outout:-600
i want difference in output as:2 hour.
can anybody figure out whats wrong with my code??
I would suggest
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
Check this fiddle
http://jsfiddle.net/shubhambhave/D9M8a/
Please, use more your mind.
First, you're not even looking at the AM or PM.
If you are sure your times will look like this (and not timestamp or anything else), you can do this (I try to keep your logic here):
var startTime = '11:30 am';
var endTime = '1:30 pm';
var st = startTime.split(':');
var ed = endTime.split(':');
if ((st[1].split(' '))[1] == 'pm')
st[0] = parseInt(st[0]) + 12;
if ((ed[1].split(' '))[1] == 'pm')
ed[0] = parseInt(ed[0]) + 12;
st[1] = (st[1].split(' '))[0];
ed[1] = (ed[1].split(' '))[0];
var diff = ((ed[0] * 60 + ed[1] * 60) - (st[0] * 60 + st[1] * 60)) / 60;
In fact, you forgot to remove the 'am' part of the time.
You also forget to calculate it.
This code can be refactored, but i'm not gonna do all the job.

Categories