clock.js, conditionally set eastern or central time - javascript

I have a perfectly functioning clock.js widget that I'm using to display date and time on multiple displays throughout our offices in several states.
The offices in the Eastern timezone have no issue, as this defaults to eastern time (our server running the screens for every display is eastern).
However, I want to add a conditional in here (say if $screenID == 3 {... so that on the screens in the Central time zone it shows the proper central time.
How should I go about adding a block in here for that condition to show central rather than eastern?
function startTime() {
var today = new Date();
var hr = today.getHours();
var min = today.getMinutes();
// var sec = today.getSeconds();
ap = (hr < 12) ? "<span>AM</span>" : "<span>PM</span>";
hr = (hr == 0) ? 12 : hr;
hr = (hr > 12) ? hr - 12 : hr;
//Add a zero in front of numbers<10
hr = checkTime(hr);
min = checkTime(min);
// sec = checkTime(sec);
document.getElementById("clock").innerHTML = hr + ":" + min + " " + ap;
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var curWeekDay = days[today.getDay()];
var curDay = today.getDate();
var curMonth = months[today.getMonth()];
// var curYear = today.getFullYear();
var date = curWeekDay+", "+curDay+" "+curMonth;
document.getElementById("date").innerHTML = date;
var time = setTimeout(function(){ startTime() }, 500);
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}

Use timezones.
function startTime(screen, loc) {
var timeZone = "America/Chicago";
if (screen === 1)
timeZone = "America/New_York";
var dateOptions = { weekday: 'long', day: 'numeric', month: 'long', timeZone: timeZone };
var timeOptions = { hour: 'numeric', minute: 'numeric', timeZone: timeZone };
var dt = new Date();
document.getElementById("myclock" + loc).innerHTML = dt.toLocaleString("en-US", timeOptions);
document.getElementById("mydate" + loc).innerHTML = dt.toLocaleString("en-NZ", dateOptions);
}
startTime(0, 1);
startTime(1, 2);
<div id="myclock1">asdf</div>
<div id="mydate1">asdf</div>
<hr>
<div id="myclock2">asdf</div>
<div id="mydate2">asdf</div>

Related

How To convert UTC into local time on the web with javascript? from http://openweathermap.org/

I am building a weather app using HTML, CSS and JavaScript.
I have succeed in displaying my current time but no luck displaying local time of the input city.
here is what it looks like:
Can I perhaps us getTimeZoneOffset() somewhere? I don't seem to figure out
function displaytheResults (weather) {
let now = new Date();
let date = document.querySelector('.location .date')
date.innerText = dateBuilder(now);
}
function dateBuilder(dt) {
let months = ['January', 'Febuary', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
let days = ['Monday', 'Tuesday', 'Wednesday','Thursday', 'Friday', 'Saturday']
let date = dt.getDate();
let year = dt.getFullYear();
let day = days[dt.getDay()];
let month = months[dt.getMonth()]
return `${day} ${date} ${month} ${year}`;
}
Once you have the offset value, pass it into this function, in order to get the time in the desired city:
function dateBuilder(city, offset) {
var date = new Date();
var utc = date.getTime() + (date.getTimezoneOffset() * 60000);
var newDate = new Date(utc + (3600000 * offset));
return `The local time in ${city} is ${newDate.toLocaleString()}`
}

Format date and time in refresh

I want to use the following script to refresh the time every second. Works fine, but I want it to output the format like this:
October 06 - 13:38:04.
How do you do that?
var timestamp = '<?=time();?>';
function updateTime(){
const firstOption = {month: 'long', day: 'numeric'};
const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
$('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions));
timestamp++;
}
$(function(){
setInterval(updateTime, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p id="time"></p>
Try this:
const firstOption = {month: 'long', day: 'numeric'};
const secondOptions = { hour: 'numeric', minute: 'numeric', second: 'numeric' };
$('#time').html(new Date(timestamp).toLocaleDateString("en-NL", firstOption) + " - " + new Date(timestamp).toLocaleTimeString("en-NL", secondOptions));
Read more about it here.
Simple function for formating your date.
function dateToString(/* add timestamp parameter if you want */) {
var d = new Date(/* timestamp parameter here */);
var months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'October',
'November',
'December',
]
var month = months[d.getMonth() - 1];
var date = (d.getDate() < 10) ? "0" + d.getDate() : d.getDate();
var hours = d.getHours(),
minutes = d.getMinutes(),
seconds = d.getSeconds();
var time = (hours < 10 ? "0" + hours : hours) + ':' + (minutes < 10 ? "0" +
minutes : minutes) + ':' + (seconds < 10 ? "0" + seconds : seconds);
return month + ' ' + date + ' - ' + time;
}
dateToString(/* pass timestamp argument here */);
Afaik PHP's time function return a unix timestamp and you're looking for an ES5 solution. This might help you.
const datetime = 1601984483;
var padStart = function(str, length) {
while (str.toString().length < length)
str = "0" + str;
return str;
}
var format = function (timestamp) {
var date = new Date();
var d = {
M: date.toLocaleString('default', { month: 'long' }),
d: padStart(date.getDate(), 2),
h: padStart(date.getHours(), 2),
m: padStart(date.getMinutes(), 2),
s: padStart(date.getSeconds(), 2)
};
return [[d.M, d.d].join(' '), [d.h, d.m, d.s].join(':')].join(' ');
}
console.log(format(datetime));

Fixed date to be use for date conversion

Is there a way I can have a fixed date that I will use for conversion.
as you can see, the code below states that it is the time in Manila, PH but when you open it given that you are in a different timezone to me it will give you different time. Date(); will just get the time in your computer.
Is there a way to get a date which will be use as a default date so that I can add or minus hours to get my desired conversion date even though it will be open in different timezones?
function showTime() {
var a_p = "";
var today = new Date();
var curr_hour = today.getHours();
var curr_minute = today.getMinutes();
var curr_second = today.getSeconds();
var months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
var myDays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
var date = new Date();
var day = date.getDate();
var month = date.getMonth();
var thisDay = date.getDay(),
thisDay = myDays[thisDay];
var yy = date.getYear();
var year = (yy < 1000) ? yy + 1900 : yy;
if (curr_hour < 12) {
a_p = "<span>AM</span>";
} else {
a_p = "<span>PM</span>";
}
if (curr_hour == 0) {
curr_hour = 12;
}
if (curr_hour > 12) {
curr_hour = curr_hour - 12;
}
curr_hour = checkTime(curr_hour);
curr_minute = checkTime(curr_minute);
curr_second = checkTime(curr_second);
document.getElementById('clock-large1').innerHTML=curr_hour + " : " + curr_minute + " : " + curr_second + " " + a_p;
document.getElementById('date-large1').innerHTML="<b>" + thisDay + "</b>, " + day + " " + months[month] + " " + year;
}
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
setInterval(showTime, 500);
<div id="clockdate-full">
<div class="wrapper-clockdate1">
<div id="clock-large1"></div>
<div id="date-large1"></div>
<div id="timezone">Manila, PH</div>
</div>
</div>
Checkout moment .js
http://momentjs.com
You can specify the time zone of the date time
var timezone = 'America/Chicago'
moment().tz(timezone).format('hh:mm:ss z')
If you can't use an external link, you should try the code below:
var opt= {
timeZone: 'America/Chicago',
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric'
},
formatDate = new Intl.DateTimeFormat([], opt)
formatDate.format(new Date())
Is there a way to get a date which will be use as a default date so that I can add or minus hours to get my desired conversion date even though it will be open in different timezones?
Yes, just specify the "fixed" date in a suitable format. Most browsers will parse ISO 8601 extended format strings like 2017-05-25T17:35:48+08:00. That represents 5:30pm in Manilla, which is UTC+08:00.
To get the equivalent time on the user's system:
var d = new Date('2017-05-25T17:35:48+08:00');
console.log(d.toString()); // equivalent local time
If you want to support browsers like IE 8, you'll need to parse the string manually or use a library with a parser, e.g. moment.js or fecha.js.

How to find ordinal position of any given weekday in JavaScript

I'm trying to find the actual position of a weekday in constant time. I get it working with loop but trying to find out it with some Mathematics. I know it is like divide it by 7 but not getting it work.
Here is the code.
for(var ind=0; ind<=between.length; ind++){
if (new Date(between[ind]).getMonthWeek() === baseDtWk && new Date(between[ind]).getDay() === baseDtD) {
datesToBeMarked.push(between[ind]);
console.log(" :Date: " + between[ind] + " :Week: " + new Date(between[ind]).getMonthWeek());
console.log("Date entered : " + new Date(between[ind]));
}
}
I have done this few days back. It is as simple as the code below. :)
On fiddle.
Number.prototype.nth= function(){
var n= Math.round(this), t= Math.abs(n%100), i= t%10;
if(i<4 && (t<4 || t> 20)){
switch(i){
case 1:return n+'st';
case 2:return n+'nd';
case 3:return n+'rd';
}
}
return n+'th';
}
Date.prototype.nthofMonth= function(){
var today= this.getDate(),m=this.getMonth(),
day= ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday',
'Friday', 'Saturday'][this.getDay()],
month= ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'][m];
return [(m+1)+'-'+today,'the ', Math.ceil(today/7).nth(), day, 'of', month, 'in', this.getFullYear()].join(' ');
}
var date=new Date().nthofMonth();
console.log(date);
You haven't shown how you want the result to look, I guess you want to know if a particular date is, say, the nth Tuesday, e.g.
// Add ordinal to a number
function addOrdinal(n) {
var ord = [,'st','nd','rd'];
var a = n % 100;
return n + (ord[a>20? a%10 : a] || 'th');
}
// Return the ordinal number of a day in the month
function ordinalDay(d) {
d = d || new Date();
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday', 'Friday','Saturday'];
return addOrdinal(Math.ceil(d.getDate()/7)) + ' ' + days[d.getDay()];
}
console.log(ordinalDay(new Date(2015,0,1))); // 1st Thursday
console.log(ordinalDay(new Date(2015,0,27))); // 4th Tuesday
console.log(ordinalDay(new Date(2015,0,31))); // 5th Saturday
console.log(ordinalDay(new Date(2015,11,25))); // 4th Friday

Alternative to toLocaleString() for chrome browser

function tolocal(str)
{
var date, split, dSplit, tSplit, d, raw;
date = '';
split = str.split(' ');
if (split.length === 2) {
dSplit = split[0].split('-');
tSplit = split[1].split(':');
}
raw = d.toLocaleString().split(' GMT')[0];
return raw.substring(raw.indexOf(", ")+2, raw.lastIndexOf(':')) + " " + raw.substring(raw.length-2,raw.length)
}
The above code, works well in ie browser where I get the output in the following format.
November 13,2012 10:15 AM
But I am not able to achieve the same in the chrome browser. Is there any other function which will help me achieve the same output? date.toUTCString() provides the same result but I am not sure how different it is to toLocaleString() in terms of functionality.
Thanks in advance.
Just do it manually:
// Where "date" is a Date object
function dateFormatUTC(date) {
var months = [
'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
var hours = date.getUTCHours();
if (hours < 10) hours = '0' + hours;
var minutes = date.getUTCMinutes();
if (hours < 10) hours = '0' + hours;
var monthName = months[date.getUTCMonth()];
var timeOfDay = hours < 12 ? 'AM' : 'PM';
return monthName + ' ' + date.getUTCDate() + ', ' +
date.getUTCFullYear() + ' ' + hours + ':' + minutes + timeOfDay;
}
maybe you can use a thirdparty library to do stuff like that: moment.js is a good one.
Example:
moment(d).format('MMMM Do, YYYY h:mms a');
you can try using options like below:
var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
// request a weekday along with a long date
var options = {weekday: "long", year: "numeric", month: "long", day: "numeric"};
// an application may want to use UTC and make that visible
options.timeZone = "UTC";
options.timeZoneName = "short";
alert(date.toLocaleString("en-US", options));
Please find the reference #
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString

Categories

Resources