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)
})
}
Related
In my application, I need to create live clock according to different timezones which are stored into database.
I have almost succeeded it.
But now I'm facing negative time in clock, and I'm out of ideas to figure out a solution.
I'm getting UTC time with the help of new Date() and calculating time with provided timezone from database.
Case 1: 0:31 (UTC time) + 5:30 (timezone) = '06:01'
Case 2: 06:31 (UTC time) - 6:30 (timezone) = '00:01'
Case 3: 5:0 (UTC time) - 7:0 (timezone) = '-02:00'
Case 1 and 2 is working properly but I'm getting negative value in 3rd case which is wrong.
I have tried to add comments in code to have better understanding of what I'm doing here. I hope it helps.
Any help will be highly appreciated.
function runClock() {
setInterval(function() {
//debugger
var time = new Date();
// take timezone from HTML element
// ex: +:5:30
var getTimezone = "-:7:0" //$("#timeZone").text();
// split into array to get oparator (Positive and Negative Timezone)
var oparator = getTimezone.split(":")[0];
var timezone = getTimezone.split(":")[1] + ":" + getTimezone.split(":")[2];
// get UTC hours
var hours = 5 //time.getUTCHours();
var minutes = 0 //time.getUTCMinutes();
var UTCTIME = timeStringToFloat(hours + ":" + minutes);
var TIMEZONEOFFSETTIME = timeStringToFloat(timezone);
var finalTime = "";
// Convert time folloed by Colon into decimals
// ex: 1:45 = 1.75
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hh = parseInt(hoursMinutes[0], 10);
var mm = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hh + mm / 60;
}
// Convert time folloed by float into Colon
// ex: 1.75 = 1:45
function floatToTime(FT) {
var splittedTime = FT.toString().split(".");
var hh = splittedTime[0];
var mm = "";
if (splittedTime[1]) {
mm = Math.round((splittedTime[1] / 100) * 60);
} else {
mm = "0";
}
finalTime = hh + ":" + ((mm < 10) ? ("0" + mm) : mm);
}
// Calculate time (UTC + or - Timezone)
// Ex: 00:15 (UTC) + 5:30 = 5:45
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
}
}
// Parse Seconds
function seconds() {
var j = "";
if (time.getUTCSeconds() < 10) {
j = "0" + time.getUTCSeconds();
} else {
j = time.getUTCSeconds()
}
return j;
}
CalcTime(UTCTIME, TIMEZONEOFFSETTIME);
$("#clockTime").text(finalTime + ":" + seconds());
}, 1000);
}
runClock();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b id="clockTime"></b>
You should just be "looping back" to 23:59 when you go negative. You can just add something to check if it goes negative then just re-add the missing time:
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
// Offset any negative times;
if (FT < 0) {
FT += 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
}
But ideally you really don't want to be handling these kinds of Timezone issues as other libraries are already handling it, i.e. moment.js
function runClock() {
setInterval(function() {
//debugger
var time = new Date();
// take timezone from HTML element
// ex: +:5:30
var getTimezone = "-:7:0" //$("#timeZone").text();
// split into array to get oparator (Positive and Negative Timezone)
var oparator = getTimezone.split(":")[0];
var timezone = getTimezone.split(":")[1] + ":" + getTimezone.split(":")[2];
// get UTC hours
var hours = 5 //time.getUTCHours();
var minutes = 0 //time.getUTCMinutes();
var UTCTIME = timeStringToFloat(hours + ":" + minutes);
var TIMEZONEOFFSETTIME = timeStringToFloat(timezone);
var finalTime = "";
// Convert time folloed by Colon into decimals
// ex: 1:45 = 1.75
function timeStringToFloat(time) {
var hoursMinutes = time.split(/[.:]/);
var hh = parseInt(hoursMinutes[0], 10);
var mm = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
return hh + mm / 60;
}
// Convert time folloed by float into Colon
// ex: 1.75 = 1:45
function floatToTime(FT) {
var splittedTime = FT.toString().split(".");
var hh = splittedTime[0];
var mm = "";
if (splittedTime[1]) {
mm = Math.round((splittedTime[1] / 100) * 60);
} else {
mm = "0";
}
finalTime = hh + ":" + ((mm < 10) ? ("0" + mm) : mm);
}
// Calculate time (UTC + or - Timezone)
// Ex: 00:15 (UTC) + 5:30 = 5:45
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
FT = FT.toFixed(2);
floatToTime(FT);
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME;
// Offset any negative times;
if (FT < 0) {
FT += 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
}
// Parse Seconds
function seconds() {
var j = "";
if (time.getUTCSeconds() < 10) {
j = "0" + time.getUTCSeconds();
} else {
j = time.getUTCSeconds()
}
return j;
}
CalcTime(UTCTIME, TIMEZONEOFFSETTIME);
$("#clockTime").text(finalTime + ":" + seconds());
}, 1000);
}
runClock();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b id="clockTime"></b>
You want to recover/display the time for a given timezone offset? Unless you like doing this for a hobby, stay away from string methods and use the date functions, no?
var offsetMS = -5.5 * 3600000
var myDate = new Date()
var dateWithOffset = new Date( myDate.getTime() + offsetMS )
var formatted = dateWithOffset.toLocaleString("en-GB",{timeZone:"UTC",hour:"numeric",minute:"numeric"})
console.log(formatted)
Even manipulating timezone offset directly is to be avoided. If you can, use toLocaleString with a real timezone name, then issues like daylight saving will be handled for you. Modern browsers support all iana timezones, so let them do the work.
Add 24 to your FT value and take division remain of 24:
function CalcTime(UTCTIME, TIMEZONEOFFSETTIME) {
if (oparator == "+") {
var FT = UTCTIME + TIMEZONEOFFSETTIME;
} else {
var FT = UTCTIME - TIMEZONEOFFSETTIME + 24;
FT = FT % 24;
}
FT = FT.toFixed(2);
floatToTime(FT);
}
Working sample: https://codepen.io/anon/pen/VqQqoo
If you do not want to use a library like moment.js that comes with time zone handling and simply need to add/subtract hours from a given date, how about converting them to a common time unit and operating on that?
const timezoneString = '-:12:30';
const parts = timezoneString.split(':');
const timezone = (parts[0] === '-' ? -1 : 1) * (parseInt(parts[1]) + (parseInt(parts[2]) / 60.0));
const timeZoneMillis = timezone * 3600 * 1000;
const now = new Date();
const inZone = new Date(now.getTime() + timeZoneMillis);
console.log(now, inZone);
Something like this would convert them to a millisecond timestamp and subtract that many hours and convert it back to a date.
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! :)
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
I have a digital clock that is running and it works great but I want to have multiple clocks running with different timezones. I am on the west coast and I would like the time to be different when people look at it in different timezones. How can I accomplish this?
function displayTime() {
var currentTime = new Date();
var hours = currentTime.getHours();
var minutes = currentTime.getMinutes();
var seconds = currentTime.getSeconds();
var meridiem = "AM";
if (hours > 12) {
hours = hours - 12;
meridiem = "PM";
}
if (hours === 0) {
hours = 12;
}
if(hours < 10) {
hours = "0" + hours;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
if(seconds < 10) {
seconds = "0" + seconds;
}
var clockDiv = document.getElementById('clock');
clockDiv.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
}
displayTime();
setInterval(displayTime, 1000);
});
To get the time in any timezone based on the current system time (which might be wrong, but that may not really matter), create a Date and just adjust the UTC time values by the required offset, then use UTC methods to build your formatted string.
e.g.
/* Return a time string in h:m:s a/p format
**
** #param {number} offsetInMinutes - offset of required timezone in minutes
** #returns {string} formatted time string
*/
function getTimeInZone(offsetInMinutes) {
function z(n) {return (n<10?'0':'') + n;}
var d = new Date();
d.setUTCMinutes(d.getUTCMinutes() + offsetInMinutes);
var h = d.getUTCHours();
return z(h%12||12) + ':' + z(d.getUTCMinutes()) + ':' +
z(d.getUTCSeconds()) + ' ' + (h<12? 'am' : 'pm');
}
// Time at UTC-08:00
document.write(getTimeInZone(-480));
You say you're "on the west coast", but not of where, so I'll assume USA where the likely timezone offset is UTC-08:00 (-480 minutes). So to always show the time in that timezone (with the usual caveat that the system clock may not be correct), you'd do:
getTimeInZone(-480);
Also note that innerText is a IE proprietary property and not supported in all browsers.
Timestamp:
1395660658
Code:
//timestamp conversion
exports.getCurrentTimeFromStamp = function(timestamp) {
var d = new Date(timestamp);
timeStampCon = d.getDate() + '/' + (d.getMonth()) + '/' + d.getFullYear() + " " + d.getHours() + ':' + d.getMinutes();
return timeStampCon;
};
This converts the time stamp properly in terms of time format, but the date is always:
17/0/1970
Why - cheers?
You have to multiply by 1000 as JavaScript counts in milliseconds since epoch (which is 01/01/1970), not seconds :
var d = new Date(timestamp*1000);
Reference
function convertTimestamp(timestamp) {
var d = new Date(timestamp * 1000), // Convert the passed timestamp to milliseconds
yyyy = d.getFullYear(),
mm = ('0' + (d.getMonth() + 1)).slice(-2), // Months are zero based. Add leading 0.
dd = ('0' + d.getDate()).slice(-2), // Add leading 0.
hh = d.getHours(),
h = hh,
min = ('0' + d.getMinutes()).slice(-2), // Add leading 0.
ampm = 'AM',
time;
if (hh > 12) {
h = hh - 12;
ampm = 'PM';
} else if (hh === 12) {
h = 12;
ampm = 'PM';
} else if (hh == 0) {
h = 12;
}
// ie: 2014-03-24, 3:00 PM
time = yyyy + '-' + mm + '-' + dd + ', ' + h + ':' + min + ' ' + ampm;
return time;
}
You can get the value by calling like convertTimestamp('1395660658')
Because your time is in seconds. Javascript requires it to be in milliseconds since epoch. Multiply it by 1000 and it should be what you want.
//time in seconds
var timeInSeconds = ~(new Date).getTime();
//invalid time
console.log(new Date(timeInSeconds));
//valid time
console.log(new Date(timeInSeconds*1000));
const timeStamp = 1611214867768;
const dateVal = new Date(timeStamp).toLocaleDateString('en-US');
console.log(dateVal)