Display and Formatting UTC Time On Static Website in Real-Time - javascript

My website currently displays UTC time like this:
2022-03-22T23:38:25.748Z
But I would like for it to be formatted like this:
23:39:22 UTC
Here is the javascript I have:
<script type="text/javascript">
function display_c(){
var refresh=1000; // Refresh rate in milli seconds
mytime=setTimeout('display_ct()',refresh)
}
function display_ct() {
var x = new Date()
var x1=x.toISOString();// changing the display to UTC string
document.getElementById('ct').innerHTML = x1;
tt=display_c();
}
<body onload=display_ct();><span id='ct' >
Can you help me format this? I've looked into using angular and searched other methods for implementing this but it seems that there are many ways to do this. The things I've tried do not display the format correctly. The code above is the closest solution I have found.

This should produce the format you want to have.
let date = new Date();
let utc_string = date.toUTCString().match(/..:..:.. .*/)[0];
console.log(utc_string);

new Date().toISOString().slice(11, 19) + ' UTC'
A nice and intentional property of the ISO datetime format is that most of the parts are always the same length.
Note that truncating, not rounding, is the correct behavior.

Use the Intl.DateTimeFormat method for this as follows:
function display_c(){
const refresh = 1000;
mytime = setTimeout('display_ct()',refresh)
}
function display_ct() {
let dtf = new Intl.DateTimeFormat("en-GB", { timeZone: "GMT", hour12: false, timeStyle: "long" });
document.getElementById('ct').innerHTML = dtf.format( new Date() );
tt = display_c();
}
display_ct();
<div id="ct"></div>
Customization:
You can either use the various configuration options available to customize the format of the datetime, or use the following setup for displaying a custom String:
function display_ct() {
let dtf = new Intl.DateTimeFormat("en-GB", { timeZone: "GMT", hour12: false, timeStyle: "medium" });
document.getElementById('ct').innerHTML = dtf.format( new Date() ) + " Zulu";
}
Available configuration options: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat

I found a web to helping you. And i give an example to you too.
https://www.codevscolor.com/javascript-iso-utc
const date = new Date('2022-03-22T23:38:25.748Z')
console.log(date.toString())
console.log(date.toUTCString())

Related

Change format date in JavaScript

I want to change the format in JavaScript, to be Year-month-day
I used this code to get 3 months before, but the format that was generated became like this 9/19/2019.
This my code:
var d = new Date();
d.setMonth(d.getMonth() - 3);
var x = d.toLocaleDateString();
console.log(x);
You can get Year, Month and Date and use string interpolation like below
var d = new Date();
d.setMonth(d.getMonth() - 3);
var formattedDate = `${d.getFullYear()}-${(d.getMonth() + 1)}-${d.getDate()}`;
console.log(formattedDate);
You can use momentjs, a lightweight and handy library for this purpose:
var d = moment(new Date()).subtract(3, 'months').format('dd-MMM-yyyy);
var x = d.toISOString().substring(0,10);
console.log(x);
//it will give you the format of y-m-d
You are using the toLocaleDateString() which will format to the result you received which is expected.
Reference Mozilla's Docs on Date() to get the right function for you there :)
Most instances you are able to just piece it together yourself similar to:
const date = `${date.getYear()}/${date.getMonth()}/${date.getDay()}`;
It's not a nice solution but there are a lot of restrictions with OOTB Date()

Remove Seconds/ Milliseconds from Date convert to ISO String

I have a date object that I want to
remove the miliseconds/or set to 0
remove the seconds/or set to 0
Convert to ISO string
For example:
var date = new Date();
//Wed Mar 02 2016 16:54:13 GMT-0500 (EST)
var stringDate = moment(date).toISOString();
//2016-03-02T21:54:13.537Z
But what I really want in the end is
stringDate = '2016-03-02T21:54:00.000Z'
There is no need for a library, simply set the seconds and milliseconds to zero and use the built–in toISOString method:
var d = new Date();
d.setSeconds(0,0);
document.write(d.toISOString());
Note: toISOString is not supported by IE 8 and lower, there is a pollyfil on MDN.
While this is easily solvable with plain JavaScript (see RobG's answer), I wanted to show you the Moment.js solution since you tagged your questions as "momentjs":
moment().seconds(0).milliseconds(0).toISOString();
This gives you the current datetime, without seconds or milliseconds.
Working example: http://jsbin.com/bemalapuyi/edit?html,js,output
From the docs: http://momentjs.com/docs/#/get-set/
A non-library regex to do this:
new Date().toISOString().replace(/.\d+Z$/g, "Z");
This would simply trim down the unnecessary part. Rounding isn't expected with this.
A bit late here but now you can:
var date = new Date();
this obj has:
date.setMilliseconds(0);
and
date.setSeconds(0);
then call toISOString() as you do and you will be fine.
No moment or others deps.
Pure javascript solutions to trim off seconds and milliseconds (that is remove, not just set to 0). JSPerf says the second funcion is faster.
function getISOStringWithoutSecsAndMillisecs1(date) {
const dateAndTime = date.toISOString().split('T')
const time = dateAndTime[1].split(':')
return dateAndTime[0]+'T'+time[0]+':'+time[1]
}
console.log(getISOStringWithoutSecsAndMillisecs1(new Date()))
function getISOStringWithoutSecsAndMillisecs2(date) {
const dStr = date.toISOString()
return dStr.substring(0, dStr.indexOf(':', dStr.indexOf(':')+1))
}
console.log(getISOStringWithoutSecsAndMillisecs2(new Date()))
This version works for me (without using an external library):
var now = new Date();
now.setSeconds(0, 0);
var stamp = now.toISOString().replace(/T/, " ").replace(/:00.000Z/, "");
produces strings like
2020-07-25 17:45
If you want local time instead, use this variant:
var now = new Date();
now.setSeconds(0, 0);
var isoNow = new Date(now.getTime() - now.getTimezoneOffset() * 60000).toISOString();
var stamp = isoNow.replace(/T/, " ").replace(/:00.000Z/, "");
Luxon could be your friend
You could set the milliseconds to 0 and then suppress the milliseconds using suppressMilliseconds with Luxon.
DateTime.now().toUTC().set({ millisecond: 0 }).toISO({
suppressMilliseconds: true,
includeOffset: true,
format: 'extended',
}),
leads to e.g.
2022-05-06T14:17:26Z
You can use the startOf() method within moment.js to achieve what you want.
Here's an example:
var date = new Date();
var stringDateFull = moment(date).toISOString();
var stringDateMinuteStart = moment(date).startOf("minute").toISOString();
$("#fullDate").text(stringDateFull);
$("#startOfMinute").text(stringDateMinuteStart);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.2/moment.js"></script>
<p>Full date: <span id="fullDate"></span></p>
<p>Date with cleared out seconds: <span id="startOfMinute"></span></p>
let date = new Date();
date = new Date(date.getFullYear(), date.getMonth(), date.getDate());
I hope this works!!
To remove the seconds and milliseconds values this works for me:
const date = moment()
// Remove milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm:ss[Z]'))
// Remove seconds and milliseconds
console.log(moment.utc(date).format('YYYY-MM-DDTHH:mm[Z]'))
We can do it using plain JS aswell but working with libraries will help you if you are working with more functionalities/checks.
You can use the moment npm module and remove the milliseconds using the split Fn.
const moment = require('moment')
const currentDate = `${moment().toISOString().split('.')[0]}Z`;
console.log(currentDate)
Refer working example here:
https://repl.it/repls/UnfinishedNormalBlock
In case for no luck just try this code
It is commonly used format in datetime in the SQL and PHP
e.g.
2022-12-25 19:13:55
console.log(new Date().toISOString().replace(/^([^T]+)T([^\.]+)(.+)/, "$1 $2") )

How to get the Australian Time Zone using Javascript? (Not JQuery)

I am trying to help a friend to get the Australian Time Zone for the University Assignment and finding difficulty.
Could someone point us in the right direction?
Thank you!
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
</script>
<p id="add"></p>
You simply use
let AuDate = new Date().toLocaleString("en-US", {timeZone: "Australia/Sydney"});
By looking at your code, looks like you are trying to get the current date and time of an Australian timezone. Lets say you want Australian Eastern Standard Time (AEST) and you want the date displayed how they would in Australia DD-MM-YYYY then do the following:
var timestamp_UTC = new Date();
var readable_timestamp_AEST = timestamp_UTC.toLocaleDateString("en-AU", {timeZone: "Australia/Sydney"}).replace(/\//g, "-") + ' ' + somestamp.toLocaleTimeString("en-AU", {timeZone: "Australia/Sydney"});
"en-AU" is the locales argument which tells the toLocalDateString to display the date as DD-MM-YYYY and the second argument is for options (timeZone is just one such possible option). Info about toLocalDateString function can be found here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
Here is some information about the Date() function https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
Hope this clears up a few things around getting times and dates from the Date() function.
I think i understand what you mean. But before that i'd like to make 2 points:
1: The Timezone() function should be called somewhere.
<script>
function Timezone() {
var x = new Date();
var currentTimeZoneOffsetInHours = x.getTimezoneOffset() / 60;
document.getElementById("add").innerHTML = currentTimeZoneOffsetInHours;
}
Timezone();
</script>
2: The convention usually is that methods start with a lower case letter. Maybe updateTimezone() would be more appropriate.
Your question can be interpreted in 2 ways now:
you want your timezone's offset in hours and for this the code above should work. getTimezoneOffset() is the way to go.
you want a human readable name of your timezone, as you can see on my site currentmillis.com (in my case it says GTB Summer). You can look in my source code to see how i achieve this:
var s = date.toString();
var iOfP = s.indexOf('('); // index of parenthesis
if (iOfP < 0) {
s = s.substring(s.lastIndexOf(' ') + 1);
} else {
s = s.substring(iOfP+1, s.length-1);
}
if (s.length > 4 && s.lastIndexOf(" Time") == s.length-5){
s = s.substring(0, s.length-5);
}
timezoneM.innerHTML = s;
This works because when you call toString() on the date the result should contain the full name of your timezone: w3schools.com/jsref/jsref_tostring_date.asp

Javascript running Date Time return value is working in chrome but not in Internet explorer

I have a javascript function to run time in different manner.
Its working well in Chrome browser but its not showing proper value in Internet Explorer.
In Chrome:
13-Dec-2011 13:14:19
In IE8:
0NaN-undefined-NaN 0NaN:0NaN:0NaN
You can view this from this page link from both the browsers. Also look at the source code of page
http://chemfluence.org.in/monetarist/sample.php
My Code:
<div id="txt" title="Industries will generate products on every 3 Virtual days.
12 Virtual Days = 1 Real day. dd-Mon-yyyy HH:MM:SS ."></div>
Javascript
<script type='text/javascript'>//<![CDATA[
var virtualOrigin = Date.parse("2012-02-27T00:00:00"),
game_start_realdate=Date.parse("2013-01-27T12:00:00"),
realOrigin = Date.now(),
factor = 12;
function getVirtual(time) {
return new Date( virtualOrigin + ((time - realOrigin) * factor) +(realOrigin-game_start_realdate)*factor);
}
function pad2(num) {
return ("0"+num).substr(-2);
}
function format(time) {
var month=new Array();
month[0]="Jan";
month[1]="Feb";
month[2]="Mar";
month[3]="Apr";
month[4]="May";
month[5]="Jun";
month[6]="Jul";
month[7]="Aug";
month[8]="Sep";
month[9]="Oct";
month[10]="Nov";
month[11]="Dec";
return pad2(time.getDate())
+ "-" + month[time.getMonth()]
+ "-" + time.getFullYear()
+ " " + pad2(time.getHours())
+ ":" + pad2(time.getMinutes())
+ ":" + pad2(time.getSeconds());
}
function startTime() {
var now = new Date();
var display = getVirtual(now);
output.innerText = format(display);
setTimeout(startTime, 1000/factor - (now.getMilliseconds() % (1000/factor)));
}
var output = document.getElementById("txt");
startTime();
</script>
I need the above Javascript to be modified to work in Internet Explore and Chrome/Firefox;
Please give me modified code;
Try using moment.js. it is cross browser and can make doing dates in javascript much less of a pain. The documentation is very thorough. http://momentjs.com/docs/
You can format your date with as little as:
var day = moment("12-25-1995", "MM-DD-YYYY");
http://momentjs.com/docs/#/parsing/string-format/
UPDATE
Here is an example of it's full usage.
var mysql_date = '2013-01-25 10:00:00'; // Date from MySQL database
/**
* #param string mysql_data Date string
* #param string format Format in which mysql_data is set
*/
var date = moment(mysql_date , 'YYYY-MM-DD HH:mm:ss'); // new moment.js object.
// To display the date in a different format use:
var date_format1 = date.format('MMM, Do'); // Format here would be Jan, 25th
var date_format2 = date.format('MMMM, Do, YYYY'); // January, 25th, 2013
console.log(date_format1, date_format2);
You can change the format when ever you want. You don't need to recreate it again.
Take a custom parse function to be sure that you can parse that date format whatever the browser is:
function parse(datestring){
var timearray = datestring.split(/[\-T\:]/g)
return +new Date(+timearray[0],timearray[1]-1,+timearray[2],+timearray[3],+timearray[4],+timearray[5])
}
And fix the pad2 function to work with IE8 by not using substr with a negative value:
function pad2(num) {
return ("0"+num).slice(-2);
}
That should do it.

Javascript DateFormat for different timezones

I'm a Java developer and I'm used to the SimpleDateFormat class that allows me to format any date to any format by settings a timezone.
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
System.out.println(sdf.format(date)); // Prints date in Los Angeles
sdf.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
System.out.println(sdf.format(date)); // Prints same date in Chicago
SimpleDateFormat is a pretty neat solution in Java but unfortunately I can't find any similar alternative in Javascript.
I'm extending the Date prototype in Javascript to do exactly the same. I have dates in Unix format but I want to format them in different timezones.
Date.prototype.format = function(format, timezone) {
// Now what?
return formattedDate;
}
I'm looking for a neat way to do this rather than a hack.
Thanks
There is a way to format for time zones.
console.log(new Date().toLocaleDateString('en-US', {timeZone: 'America/Denver'}))
// 11/13/2018
console.log(new Date().toLocaleTimeString('en-US', {timeZone: 'America/Denver'}))
// 2:30:54 PM
console.log(new Date().toLocaleTimeString('en-US', {timeZone: 'America/New_York'}))
// 4:31:26 PM
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString
The ISO Extended format for common date is YYYY-MM-DD, and for time is hh:mm:ss. Either format can be understood, unambiguously, worldwide.
See also:
http://jibbering.com/faq/#dates
If you're just passing the raw TZ there's nothing really complicated about adjusting the hours.
My example below is of course abbreviated. Yours may get quite long depending on how many patterns you'd handle.
Date.prototype.format = function(format, tzAdjust) {
// adjust timezone
this.setHours(this.getHours()+tzAdjust)
// pad zero helper - return "09" or "12"
var two = function(s){ return s+"".length==1 ? "0"+s : s+""; }
// replace patterns with date numbers
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
switch(pattern){
case "d" : return this.getDate();
case "dd" : return two(this.getDate());
}
});
}
Attempting to (ever so slightly) improve upon mwilcox's suggestion:
Date.prototype.format = function(format, tzAdjust) {
// get/setup a per-date-instance tzDate object store
var tzCache = this.__tzCache = this.__tzCache || (this.__tzCache = {});
// fetch pre-defined date from cache
var tzDate = tzCache[tzAdjust];
if ( !tzDate )
{
// on miss - then create a new tzDate and cache it
tzDate = tzCache[tzAdjust] = new Date( this );
// adjust by tzAdjust (assuming it's in minutes
// to handle those weird half-hour TZs :)
tzDate.setUTCMinutes( tzDate.getUTCMinutes()+tzAdjust );
}
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
// replace each format tokens with a value
// based on tzDate's corresponding UTC property
});
}
You are clearly asking two questions in one, formatting and time zone. They need to be addressed separately. Formatting is pretty trivial, if none of the other answers will do for that you will have to be more specific.
As for the time and time zone, if you have your server inject the UTC time, preferably as UNIX time in milliseconds, into the JavaScript, you can compare that to the time on the client machine, and thus work out how far from UTC the client is. Then you can calculate the time of any time zone you want.
Edit: I actually didn't know JavaScript also had built in UTC time until I checked on the internet, neat.
In any case, I suppose this is want you want:
Date.prototype.format=function(format,timezone){
var obj=new Date(this.getTime()+this.getTimezoneOffset()*60000+timezone*3600000);
var two=function(s){
return s<10?"0"+s:s+"";
}
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
switch(pattern){
case "dd" : return two(obj.getDate());
case "MM" : return two(obj.getMonth()+1);
case "yyyy" : return obj.getFullYear();
case "hh" : return two(obj.getHours());
case "mm" : return two(obj.getMinutes());
case "ss" : return two(obj.getSeconds());
}
});
}
You can add in more patterns if you need.
Don't write your own stuff; just get datejs: http://www.datejs.com/
You can figure out what the timezone offset is set to in the execution environment like this:
var local = new Date();
var utc = Date.UTC(local.getFullYear(), local.getMonth(), local.getDate(), local.getHours(), local.getMinutes(), local.getSeconds(), local.getMilliseconds());
var tz = (utc - local.getTime()) / (60 * 60 * 1000);
This is an old question, but since I found it:
As mentioned, there's nothing reasonable built-in.
As for libs, there is Moment Timezone for Moment.js.
Here is a JSfiddle with an example: http://jsfiddle.net/kunycrkb/
The same code inline:
var m = moment("2014-06-01T13:05:00Z");
var f = "HH:mm z";
$("#results").text(m.tz("UTC").format(f) + " is " + m.tz("EST").format(f) + "!");
Since my requirement was a typescript solution but I stumbled here I used this answer to write my typescript function.
Based on answer above, a function in typescript which converts a timestamp or a date object into a formatted local time string.
const formatDateString = (date_or_ts:Date|number):string=>{
let obj:Date;
if(typeof date_or_ts === "number"){
obj = new Date(date_or_ts*1000);
// obj=new Date(obj.getTime()+obj.getTimezoneOffset()*60000+timezone*3600000);
}else{
obj = date_or_ts;
}
const format = "dd-MM-yyyy hh:mm:ss";
let two=function(s:number){
return s<10?"0"+s:s+"";
}
return format.replace(/dd|MM|yyyy|hh|mm|ss/g, function(pattern){
const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
switch(pattern){
case "dd" : return two(obj.getDate()).toString();
case "MM" : return months[obj.getMonth()];
case "yyyy" : return obj.getFullYear().toString();
case "hh" : return two(obj.getHours()).toString();
case "mm" : return two(obj.getMinutes()).toString();
case "ss" : return two(obj.getSeconds()).toString();
default: return "";
}
});
}

Categories

Resources