Fixed date to be use for date conversion - javascript

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.

Related

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));

JS: Formatting ISO Date String to Custom Format?

I have an ISO Date string such as "2020-08-12T03:02:47Z". I want to convert these to "August 12, 2020 3:02PM". Would I have to concert it to a timestamp and work backwards to accomplish this?
you should look at the moment.js package
npm i moment
console.log(moment(yourVariable).format('LLLL'))
https://momentjs.com/docs/
You can use formatting options of the Internationalization API. For instance like this:
let fmt = new Intl.DateTimeFormat('en-US', {
dateStyle: "long",
timeStyle: "short",
timeZone: "UTC",
hour12: true
});
// Demo
let str = fmt.format(new Date("2020-08-12T03:02:47Z"));
console.log(str); // "August 12, 2020 at 3:02 AM"
// Optional: when you don't like the "at" or the space before "AM" or "PM":
str = str.replace(/ (..)$| at\b/g, "$1");
console.log(str); // "August 12, 2020 3:02AM"
You had to build a new date and from this get the values and reformat them.
For month use an array. For the hours get AM/PM and the hours (0-12/0-11 = 0-23). For the 2-digit minutes add before a string "0" and get than the last 2 chars. For hours you could even so but you show us hours as 1-digit.
const MONTH = ['January,', 'February', 'March', 'April', 'May', 'June', 'JUly', 'August', 'September', 'October', 'November', 'December'];
let date = new Date ('2020-08-12T03:02:47Z');
let time = date.getHours();
let hours = (time<13) ? time : time % 12;
let amPm = hours >= 12 ? 'PM' : 'AM'
date = MONTH[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear() + ' ' + hours + ':' + ('0' + date.getMinutes()).slice(-2) + amPm;
console.log(date);
Ciao, try to use moment suing format 'LLL'. Like this:
let date = '2020-08-12T03:02:47Z'
console.log(moment(date).format('LLL'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

clock.js, conditionally set eastern or central time

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>

Formatting a Javascript String date to a specifc format

I have a String like 2016/1/1, which I want to change into a proper format like 2016/01/01 (yyyy/mm/dd). The output format should also be a String.
What is the correct way to do it?
Here's a piece of code I often use:
function yyyymmdd(dte) {
var _date = new Date(dte);
var mm = _date.getMonth() + 1; // getMonth() is zero-based
var dd = _date.getDate();
return [_date.getFullYear(),
"/",
(mm>9 ? '' : '0') + mm,
"/",
(dd>9 ? '' : '0') + dd
].join('');
}
var date = "1/1/2010";
yyyymmdd(dte); // returns "2010/01/01"
This is simple a format I've come up with that I like. There are probably many ways to approach this code.
This is a slightly cleaner version that was suggested to me later.
function yyyymmdd(dte) {
var _date = new Date(dte);
var mm = _date.getMonth() + 1; // getMonth() is zero-based
var dd = _date.getDate();
return [_date.getFullYear(),
(mm>9 ? '' : '0') + mm,
(dd>9 ? '' : '0') + dd
].join('/');
}
Handling dates in Javascript can be a pain, an alternate solution is to use momentjs
The library can be found here
You can then easily format date in various different formats using the .format() option:
var dateTime = new Date();
dateTime = moment(dateTime).format("YYYY/MM/DD");
Using Datejs, you pass a format to .toString().
Example
Date.parse('2016/1/1').toString('yyyy-MM-dd')
// "2016-01-01"
Hope this helps.
var now = new Date();
var date = now.getDate();
var month = now.getMonth() + 1;
var monthName = ['January', 'February', 'March', 'April', 'May', 'June', 'July','August','September', 'Octobor', 'November', 'December']
var year = now.getFullYear();
if (date <= 9) {
date = '0'+ date
}
console.log(date + '-' + monthName[month] + '-' +year);

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