I've made an object that displays the date and time live.
I would like to know how I can separate the time part from the date so I can have it in its own HTML element so I can apply different styling to it?
I'm not that advanced with JavaScript, and I find working with the date object very complicated.
LiveDateTime.js
'use strict';
function LiveDateTime(dateEl, options) {
this.dateEl = dateEl;
this.options = options;
this.timestamp;
this.offset;
this.start();
}
LiveDateTime.prototype = {
start: function () {
var now = !this.timestamp ? new Date() : new Date(this.timestamp),
self = this;
(function update() {
self.dateEl.innerHTML = now.toLocaleString(self.options.locale, self.options);
now.setSeconds(now.getSeconds() + 1);
self.timeoutId = setTimeout(update, 1000);
})();
},
stop: function () {
clearTimeout(this.timeoutId);
this.timeoutId = undefined;
}
};
Usage
var liveDateTime = new LiveDateTime(document.getElementById('date'), {
locale: 'FR',
weekday: 'long',
day: 'numeric',
month: 'long',
year: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
//output example: vendredi 13 mars 2015 23:14:12
HTML
<span id="date"></span> - <span id="time"></span>
Use date.toLocaleDateString() for the date part, and date.toLocaleTimeString() for the time part.
You can format your date using Date available methods:
var now = new Date()
var date = now.toLocaleDateString();
var time = now.toLocaleTimeString();
console.log(date + ' ' + time)
You can use javascript's split() method
var date = liveDateTime.split(" ");
var weekday = date[0];
var day = date[1];
var month = date[2];
var year = date[3];
var time = date[4].split(":");
var hour = time[0];
var minute = time[1];
var second = time[2];
I'm not that advanced with JavaScript, and I find working with the date object very complicated.
Working with date in JS could be indeed complicated and frustrating. But that could be a pleasure by using libraries such momentjs
So as to get the date formatted as you need :
moment().format('dddd Do MMMM YYYY'); // vendredi 13 mars 2015 (with FR locale)
// Friday 13th March 2015 (with EN locale)
And for getting the hour :
moment().format('H:mm:ss'); // 23:36:15
These are just tiny examples of the possibilities of the library.
For other formatting patterns, refer to this table of the documentation
var now = new Date()
var date = now.toLocaleDateString();
var time = now.toLocaleTimeString();
console.log(date + ' ' + time)
Related
I have a Date. It is in the local timezone. I want a new Date that is at the beginning of the dayin a different timezone. Here are some things I do not want:
A Date in UTC equivalent to the first date converted to UTC
A string
Specifically, UTC does not work because getting the start of a day in UTC is not the same as getting the start of the day in a timezone.
So If I have a date in Calcutta and want to get the start of that day in San Francisco, the date in Calcutta and the date in Greenwich might not be the same date. It could be June 15th in Calcutta, June 15th in Greenwich, but June 2nd in San Francisco. So calling setMinutes(0) etc on a date that is set to UTC will not work.
I am also using date-fns (not moment) if that's helpful, but it doesn't seem to be because all dates (including those in date-fns-tz) are returned in either local or UTC time.)
Is this possible in Javascript or am I insane?
Note:
This is not the same as Convert date to another timezone in JavaScript
That is about converting to strings. I do not want strings.
One way is to:
Get the current timezone offset at the required location
Create a date for the required UTC date
Apply the offset from #1
e.g. using the answer at Get Offset of the other Location in Javascript:
function getTimezoneOffset(date, loc) {
let offset;
['en','fr'].some(lang => {
let parts = new Intl.DateTimeFormat(lang, {
minute: 'numeric',
timeZone: loc,
timeZoneName:'short'
}).formatToParts(date);
let tzName = parts.filter(part => part.type == 'timeZoneName' && part.value);
if (/^(GMT|UTC)/.test(tzName[0].value)) {
offset = tzName[0].value.replace(/GMT|UTC/,'') || '+0';
return true;
}
});
let sign = offset[0] == '\x2b'? '\x2b' : '\x2d';
let [h, m] = offset.substring(1).split(':');
return sign + h.padStart(2, '0') + ':' + (m || '00');
}
// Convert offset string in ±HH:mm to minutes
function offsetToMins(offset) {
let sign = /^-/.test(offset)? -1 : 1;
let [h, m] = offset.match(/\d\d/g);
return sign * (h * 60 + Number(m));
}
// Format date as YYYY-MM-DD at loc
function formatYMD(loc, date) {
let z = n => ('0'+n).slice(-2);
let {year, month, day} = new Intl.DateTimeFormat('en',{timeZone: loc})
.formatToParts(date)
.reduce((acc, part) => {
acc[part.type] = part.value;
return part;
}, Object.create(null));
return `${year}-${z(month)}-${z(day)}`
}
// Return stat of day for date at loc
function startOfDayAtLoc(loc, date = new Date()) {
let offset = getTimezoneOffset(date, loc);
let offMins = offsetToMins(offset);
let d = new Date(+date);
d.setUTCHours(0, -offMins, 0, 0);
// If date is + or - original date, adjust
let oDateTS = formatYMD(loc, date);
let sodDateTS = formatYMD(loc, d);
if (sodDateTS > oDateTS) {
d.setUTCDate(d.getUTCDate() - 1);
} else if (sodDateTS < oDateTS) {
d.setUTCDate(d.getUTCDate() + 1);
}
return d;
}
// QnD formatter
let f = (loc, d) => d.toLocaleString('en-gb', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour12:false,
hour: '2-digit',
minute: '2-digit',
second: '2-digit',
timeZone: loc,
timeZoneName: 'long'
});
// Examples
// 1 June 2020 00:00:00 Z
let d = new Date(Date.UTC(2020, 5, 1));
['America/New_York',
'Asia/Tokyo',
'Pacific/Tongatapu',
'Pacific/Rarotonga'
].forEach(loc => {
let locD = startOfDayAtLoc(loc, d);
console.log(loc + ' ' + getTimezoneOffset(d, loc) +
'\nZulu : ' + locD.toISOString() +
'\nLocal: ' + f(loc, locD));
});
// Dates on different date to UTC date
let laDate = new Date('2022-04-30T18:00:00-07:00');
let la = 'America/Los_Angeles';
console.log(`${la} - ${f(la, laDate)}` +
`\nStart of day: ${f(la, startOfDayAtLoc(la, laDate))}`
);
let chaDate = new Date('2022-05-01T03:00:00+10:00');
let cha = 'Pacific/Chatham';
console.log(`${cha} - ${f(cha, chaDate)}` +
`\nStart of day: ${f(cha, startOfDayAtLoc(cha, chaDate))}`
);
However, I'd suggest you use a library with timezone support as there are many quirks with the Date object and there is a new Temporal object in the works.
This question already has answers here:
jQuery date formatting
(24 answers)
How do I format a date in JavaScript?
(68 answers)
Closed 3 years ago.
When using this method, my time is returning, the values with month name, time zone and so on.
It's returning as follows: newDate = Mon Sep 02 2019 12:00:00 GMT-0300 (Brasilia Standard Time)
How would I return the format dd / MM / YYYY - hh / MM
sistema.conversao = {
converterParaDate: function (dataPtbr) {
//data virá em formato pt-br dd/mm/aaaa hh:mm
var arrDataHora = dataPtbr.split(" "); //separar a data dos minutos
var data = arrDataHora[0];
var arrHora = [];
if (arrDataHora.length > 1)
arrHora = arrDataHora[1].split(":");
var dia, mes, ano;
var arrData = data.split("/");
day= parseInt(arrData[0]);
mouth= parseInt(arrData[1]) - 1;
year= parseInt(arrData[2]);
var hour= 0, minute= 0, second= 0;
if (arrHora && arrHora.length > 0) {
hora = arrHora[0];
minuto = arrHora[1]
}
var newDate = new Date(year, mouth, day, hour, minute, second)
return newDate;
}
}
You need to separate every part of the Date object you just created and then rearrange it in any way you need it.
var day = newDate.getDate();
var month = newDate.getMonth();
var year = newDate.getFullYear();
var hours = newDate.getHours();
var minutes = newDate.getMinutes();
var formatDate = day + "/" + month + "/" + year + " - " + hours + "/" + minutes;
return formatDate;
EDIT:
Read more about Date methods: https://www.w3schools.com/js/js_date_methods.asp
Another option would be to use the native JS method toLocaleDateString() to do the formatting. It's easy to change the options to produce different date formatting requirements.
var date = new Date();
var options = {
day: 'numeric',
month: 'numeric',
year: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: false
};
var newDate = date.toLocaleDateString('en-US', options).replace(', ', ' - ').replace(':', '/');
console.log(newDate);
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
So far I have created a timezone list for PST, CST, EST, GMT, CEST, IST, AST which works perfectly. But I also want to add an input box that will always be PST and output a local time from it..
i.e. if a user puts in 09:00 then if they live in the UK it will output 17:00
So it basically registers where you are in relation to timezone and adds (or subtracts) from the inputted time. (UK is +8 so input + 8 gives output)
This is my FIDDLE of where I am at right now
https://jsfiddle.net/wayneker/unc7e64f/16/
Although I know this demo is ideal, I know I cannot currently make this (with my current knowledge).
https://greenwichmeantime.com/time/to/pst-local/
I have researched various pages and cannot understand a lot of them. But what I have seen is normally local to PST
window.setInterval(function(){
// function to calculate local time
// in a different city
// given the city's UTC offset
function calcTime(offset) {
//function calcTime(city, offset) {
// create Date object for current location
d = new Date();
//set options
var options = { weekday: "short", year: "numeric", month: "short",
day: "numeric", hour: "numeric", minute: "numeric", second: "numeric" };
// convert to msec
// add local time zone offset
// get UTC time in msec
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
// create new Date object for different city
// using supplied offset
nd = new Date(utc + (3600000*offset));
// return time as a string
//return "The local time in " + city + " is " + nd.toLocaleString();
//return nd.toLocaleString();
return nd.toLocaleString("en-US", options);
}
Date.prototype.stdTimezoneOffset = function() {
var jan = new Date(this.getFullYear(), 0, 1);
var jul = new Date(this.getFullYear(), 6, 1);
return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}
Date.prototype.dst = function() {
return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
var today = new Date();
if (today.dst()) document.getElementById('dst').innerHTML = '';
Here is one way is to convert the PST time back to UTC and then apply the local offset.
function submitfunction() {
var value = document.getElementById("PSTPDT").value;
var parts = value.split(':');
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var date = now.getDate();
var offset = now.getTimezoneOffset()
var local = new Date(year, month, date, parts[0], parts[1], parts[2]);
local.setMinutes(local.getMinutes() + 420 - offset);
var result = document.getElementById("result");
result.innerHTML = local
}
See example:
https://jsfiddle.net/p9u5j8dm/
I want to show time in 12 hours format without using the AM and PM. For example 3:45 only and not 3:45 PM or 3:45 AM. How I can modify the toLocaleTimeString() to not show the PM AM but in 12 number format?
var minsToAdd = 45;
var time = "15:00";
var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
console.log(newTime);
.toLocaleTimeString() did not have any override to do so.
There are multiple ways to do so.
Replace AM/PM by blank:
var minsToAdd = 45;
var time = "15:00";
var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000).toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit', hour12: true });
console.log(newTime.replace("AM","").replace("PM",""));
Using custom JavaScript function:
function formatTime(d) {
function z(n){return (n<10?'0':'')+n}
var h = d.getHours();
return (h%12 || 12) + ':' + z(d.getMinutes());
}
var minsToAdd = 45;
var time = "15:00";
var newTime = new Date(new Date("2000/01/01 " + time).getTime() + minsToAdd * 60000);
console.log(formatTime(newTime));
formats below assume the local time zone of the locale;
America/Los_Angeles for the US
US English uses 12-hour time with AM/PM
console.log(date.toLocaleTimeString('en-US'));
"7:00:00 PM"
For more information, visit official docs here
it's very ez.
const date24 = new Date();
const data24Time = date24.toLocaleTimeString('en-IT', { hour12: false })
console.log("24 h : ",data24Time)
// 24 h : 20:26:09
const date12 = new Date();
const data12Time = date12.toLocaleTimeString('en-IT')
console.log("12 h : ",data12Time)
// 12 h : 8:26:09 PM
// toLocaleTimeString('{languege for show time}-{languege for set}')
I need something obvious pointing out to me in regard to JS functions.
The following code works, but I want to call upon it anywhere:
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var date = entry.date.split(' ');
var date = date[0];
var date = new Date(date.replace(pattern,'$3-$2-$1'));
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
What would be the best practice to place this in a global function so I can just do adjustDate(string). Double points (Sadly, not in my power) to explain how I would then also have access to all the objects such as year, month, day.
Thanks in advance!
Can't you just declare the function?
function adjustDate(entry) {
var date = entry.date.split(' ');
date = date[0];
date = new Date(date.replace(/(\d{2})\-(\d{2})\-(\d{4})/, '$3-$2-$1'));
return {
year: date.getYear(),
month: date.getMonth(),
day: date.getDay()
};
}
I would just return a date without abstracting its existing methods
function AdjustedDate(dateString)
{
return new Date(dateString.split(' ')[0].replace(/(\d{2})\-(\d{2})\-(\d{4})/, '$3-$2-$1'));
}
var ad = AdjustedDate(entry.date);
alert(ad);
alert(ad.getDay());
Pass the entry into the function and then pass an object containing the information you want out. Then just access it like you would an ordinary JS object.
function adjustDate(entry) {
var pattern = /(\d{2})\-(\d{2})\-(\d{4})/;
var date = entry.date.split(' ');
var date = date[0];
var date = new Date(date.replace(pattern,'$3-$2-$1'));
var year = date.getYear();
var month = date.getMonth();
var day = date.getDay();
return { day: day, month: month, year: year }
}
var dateObject = adjustDate(/*entry*/)
dateObject.day // day
dateObject.month // month