How to set timezone in jquery countdown timer - javascript

I want to set GMT+5:30 as my timezone in jquery countdown.
Start Time for countdown is 'Thu May 20 16:00:00 IST 2010'
End Time is 'Thu May 20 17:00:00 IST 2010' as value.
+330 is my timezone given in minutes.
But my countdown starts from 00:35:00.
I would have expected the countdown to start from 01:00:00
Not sure why this is discrepancy is there.
<script type="text/javascript">
$(function () {
var endTime = '#{myBean.getCountDownDate()}';
$('#defaultCountdown').countdown({
until: endTime, format: 'HMS',
timezone: +330,
compact: true, description: '#{myBean.getCountDownDate()}'});
});
</script>

When using the until parameter the countdown plugin counts down until that time.
This will run for one hour using the correct offset.
$('#countdown').countdown({
until: $.countdown.UTCDate(+330, 2010, 6-1, 20, 17),
format: 'HMS',
compact: true
});
Since 2010:06:20:17 has already passed it will display 00:00:00.
I would bet the reason you got 00:35:00 in your countdown is that you were looking at it around 2010:06:20:16:25.

What happens when you change your End Time format to 'Thu, 20 May 2010 17:00:00 IST'?
-edit-
It looks like you're not supposed to pass the date value to until as a String. You can pass in a Date to specify the exact date/time, but a string is only supposed to be used as a time offset, which is why you always get the same amount of time remaining when you refresh.
I couldn't get Date to convert the string with the 'IST' time zone, so I ended up using 'GMT+05:30'. I also put the timezone offset in terms of hours instead of minutes.
<script type="text/javascript">
$(function () {
var endTime = "Tue, 29 Jun 2010 12:00:00 GMT+0530";
$('#defaultCountdown').countdown({
until: new Date(endTime), format: 'HMS',
timezone: +5.5,
compact: true, description: endTime.toString()});
});
</script>

to set timer with eastern timezone
<script>
setInterval(function(){
var timeZone = "America/New_York";
var TimerEndDate = "Nov 25 2022";
var endHour = 23;
var endMinute = 59;
var endSeconds = 59;
//for starting time for timer
//bydefault set to america current time
var nowDate = new Date();
var nowTimeZone = convertTZ(nowDate, timeZone);
var now = new Date(nowTimeZone.getFullYear(),nowTimeZone.getMonth(),nowTimeZone.getDate());
now.setHours(nowTimeZone.getHours(), nowTimeZone.getMinutes(), nowTimeZone.getSeconds());
var endDate = new Date(TimerEndDate+" "+endHour+":"+endMinute+":"+endSeconds);
var endDateTime = convertTZ(endDate, timeZone);
var future = new Date(endDateTime.getFullYear(),endDateTime.getMonth(),endDateTime.getDate());
future.setHours(endHour, endMinute, endSeconds);
var difference = Math.floor((future - now) / 1000);
var seconds = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var minutes = fixIntegers(difference % 60);
difference = Math.floor(difference / 60);
var hours = fixIntegers(difference % 24);
difference = Math.floor(difference / 24);
var days = difference;
$("#seconds").text(seconds + "s");
$("#minutes").text(minutes + "m");
$("#hours").text(hours + "h");
$("#days").text(days + "d");
}, 1000);
function convertTZ(date, tzString) {
return new Date((typeof date === "string" ? new Date(date) : date).toLocaleString("en-US", {timeZone: tzString}));
}
function fixIntegers(integer)
{
if (integer < 0)
integer = 0;
if (integer < 10)
return "0" + integer;
return "" + integer;
}
</script>
<span id="days"></span>
<span id="hours"></span>
<span id="minutes"></span>
<span id="seconds"></span>

Related

Calculating time with momentjs

I'm having start_time which is in string and AM/PM format, with a time interval, now my idea is to put start _time in while loop where it is being added with time interval and be in the loop until it becomes greater than current_time, I want to pull out next current time within this interval.
Let's suppose
start_time => 10:00 AM
current_time => moment()
time_interval => 15 mins
So if any user calls this function at 10:05 AM then I want output to be 10:15 AM, or any user calls this function at 12:33 PM so my output will be 12:45 PM and so on.
To achieve this I'm trying something like this:
nextDrawTime() {
let moment = require('moment');
let now = moment();
let set_time = moment(now.get('date') + ' ' + this.start_time).get('time');
while(set_time > moment) {
set_time.add(this.time_interval, 'm');
}
return set_time.format('LT');
}
But somehow this is not working out. Help me out with it. Thanks.
You forgot to call moment.
while(set_time > moment())
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
<script>
function nextDrawTime() {
let now = moment();
start_time = '10:00 AM';
let set_time = moment( now.format("YYYY-MM-DD") + ' ' + start_time).get('time');
while( set_time < moment() ) {
set_time.add(15, 'm');
}
return set_time.format('LT');
}
console.log(nextDrawTime());
</script>
now.get('date') just returns the int 11 - you need to create today as a full string then compare, also you need to check less than <
In this case it's far more effective working with the Unix Timestamp.
var interval = 15 * 60; // interval in seconds = 15 minutes
var next15 = moment(((Math.floor(moment().unix() / interval) * interval) + interval) * 1000)
console.log(next15.format("YYYY-MM-DD HH:mm:ss"))
function nextDrawTime(time, format = "LT", interval = 15) {
const next = moment(time, format);
const roundedMinute = Math.ceil(next.minute() / interval) * interval;
return next
.minutes(0)
.seconds(0)
.add(roundedMinute, "minutes")
.format(format);
}
nextDrawTime(moment().format("LT"))
console.log("10:05 AM =>", nextDrawTime("10:05 AM"));
console.log("12:33 PM =>", nextDrawTime("12:33 PM"));
console.log("11:59 AM =>", nextDrawTime("11:59 AM"));
console.log("11:59 PM =>", nextDrawTime("11:59 PM"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Works for different time formats and intervals
nextDrawTime(
"Tuesday, December 31th 2019, 11:59:59 pm", // Time
"dddd, MMMM Do YYYY, h:mm:ss a" // Format
60, // Interval
)
// Wednesday, January 1st 2020, 12:00:00 am

Javascript timestamp grouped by X minutes

I want to create timestamp list grouped by X minutes.
For instance I have min data value and max date timestamp value.
minDate = 1524548466000; // Tuesday, April 24, 2018 5:41:06 AM
maxDate = 1524577986000; // Tuesday, April 24, 2018 1:53:06 PM
So I want to create timestamp array start with Tuesday, April 24, 2018 5:40:0 AM to Tuesday,April 24, 2018, 1:55:00 PM using javascript.
I want this output:
[1524548400000,1524548700000,1524549000000,...1524578100000]
How can I do this?
Here is my solution. I just count second and compare with maxDate.
var minDate = new Date(1524548466000); // Tuesday, April 24, 2018 5:41:06 AM
var maxDate = new Date(1524577986000); // Tuesday, April 24, 2018 1:53:06 PM
var listTimestamp = [];
while (minDate.getTime() !== maxDate.getTime()) {
minDate.setSeconds(minDate.getSeconds() + 1);
listTimestamp.push(minDate.getTime());
}
console.log(listTimestamp);
Here the function you needed
function timestampGrouping(minDate, maxDate, x){
var gap = x * 60000 //60000 = 1minute;
minDate = Math.floor(minDate/gap)*gap;
maxDate = Math.ceil(maxDate/gap)*gap;
var arr = [];
while(minDate <= maxDate){
arr.push(minDate);
minDate += gap;
}
return arr;
}
var groupingArr = timestampGrouping(1524548466000, 1524577986000, 5);
console.log(groupingArr);
Math.floor and Math.ceil is to find the nearest gap value you required, and just loop thought the value to get all the minute gap you want.
minDate, maxDate and gap value can be anything you wish to.
Hope this is what you required.
You could divide the given Unix Time (Epoch Time) and divide it by a product of wanted minutes, seconds and 1000 for miliseconds.
5 minutes * 60 seconds * 1000 milliseconds = 300000
For moving events in the same slot use
Math.floor(time / 300000)
if duration is 5 min then you can set duration variable as follows.
var duration = 5 * 60 * 1000;
endTime = endTime - endTime % duration;
startTime = startTime - startTime % duration;
for(var i=startTime;i<endTime;i+=duration){
arr.push(i);
}

Converting a time string to a time value in javascript

I have a string that looks like "01:12:33" which is HH:MM:SS format. How can I convert that to a time value in JS?
I've tried the new Date() constructor and setting the year and day values to 0, then doing getTime(), but I am not having any lucky.
Prefix it with a date:
var hms = "01:12:33";
var target = new Date("1970-01-01T" + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the start of the day;
Or, if you need it to be today's date:
var now = new Date();
var nowDateTime = now.toISOString();
var nowDate = nowDateTime.split('T')[0];
var hms = '01:12:33';
var target = new Date(nowDate + 'T' + hms);
console.log(target);
There target.getTime() will give you the number of milliseconds since the epoch.
You can add the following function that does the job for you :
function getDateFromHours(time) {
time = time.split(':');
let now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate(), ...time);
}
console.log(getDateFromHours('01:12:33'));
To be able to do this, there should be a conversion of the string in HH:MM:SS format to JavaScript time.
Firstly, we can use Regular Expression (RegEx) to properly extract the values in that string.
let timeString = "01:12:33";
Extract values with RegEx
let regExTime = /([0-9]?[0-9]):([0-9][0-9]):([0-9][0-9])/;
let regExTimeArr = regExTime.exec(timeString); // ["01:12:33", "01", "12", "33", index: 0, input: "01:12:33", groups: undefined]
Convert HH, MM and SS to milliseconds
let timeHr = regExTimeArr[1] * 3600 * 1000;
let timeMin = regExTimeArr[2] * 60 * 1000;
let timeSec = regExTimeArr[3] * 1000;
let timeMs = timeHr + timeMin + timeSec; //4353000 -- this is the time in milliseconds.
In relation to another point in time, a reference time has to be given.
For instance,
let refTimeMs = 1577833200000 //Wed, 1st January 2020, 00:00:00;
The value above is is the number of milliseconds that has elapsed since the epoch time (Jan 1, 1970 00:00:00)
let time = new Date (refTimeMs + timeMs); //Wed Jan 01 2020 01:12:33 GMT+0100 (West Africa Standard Time)

16 digit timestamp to Javascript date format

I am getting a 16-digit Timestamp from the server.
For example : I got "1485157072432000" from the server and when I use the time stamp converter it is showing as Wed Oct 03 49032 04:43:52 GMT+0530 (India Standard Time)
However,I am getting the exact time when I remove the last 3-digits from the 16-digit number. But I'm getting 16 digit Timestamp from server. What is the way to get exact time from 16-digit Timestamp??
Since you need the microseconds precision I guess that the only solution is to use a custom object where you store all the information you need.
I would suggest you to use something like this utility developed by the GitHub user kamikane.
In particular you need the parse function that he developed:
function parse(nano) {
var ms = nano / 1000;
var ss = ms / 1000;
var mm = ss / 60;
var hh = mm / 60;
var dd = hh / 24;
var microseconds = Math.round((ms % 1) * 1000);
var milliseconds = Math.floor(ms % 1000);
var seconds = Math.floor(ss % 60);
var minutes = Math.floor(mm % 60);
var hours = Math.floor(hh % 24);
var days = Math.floor(dd);
return { microseconds: microseconds, milliseconds: milliseconds, seconds: seconds, minutes: minutes, hours: hours, days: days, toString: toString };
};
Example usage:
parse(1485157072432010);
{ microseconds: 10, milliseconds: 432, seconds: 52, minutes: 37, hours: 7, days: 17189 }

problem with changes GMT( time zone )?

I created a small script to display the time(UTC-+3.5). The problem is there that changes GMT(+4.5, +3.5) in Iran every six months in year, and changes Time is pulled back and forth (Daylight Saving)
How i set yourself clock with change GMT in iran? what do i do? (now GMT in iran is +4.5)
EXAMPLE: my code-jsfiddle
var int = self.setInterval("clock()", 1000);
function clock() {
var d = calcTime('+4.5')
var t = d.toLocaleTimeString();
document.getElementById("clock").innerHTML = t;
}
function calcTime(offset) {
d = new Date();
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000 * offset));
return nd;
}
With respect
Fiddle Example
<script type="text/javascript">
var int = self.setInterval("clock()", 1000);
function clock() {
var d = calcTime('+4.5')
var t = d.toLocaleTimeString();
document.getElementById("clock").innerHTML = t;
}
function calcTime(offset) {
d = new Date();
ds = new Date(); // new Daylight Savings Time object
ds.setMonth(9); // Set month to september
ds.setDate(21); // set day to 21st
if(d > ds){ // if current date is past the daylight savings date minus one from the offset
offset = eval(offset - 1);
}
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
nd = new Date(utc + (3600000 * offset));
return nd;
}
</script>
<b id="clock"></b>
This works. It will check if the date is currently past September 21st and if it is it will -4.5 from GMT otherwise 3.5
it is not the cleanest code i've ever written, I just modified yours. however you can see how it is done now.

Categories