How to use toLocaleTimeString 12 hours time without AM/PM abbreviations? - javascript

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}')

Related

Get the local date instead of UTC

The following script calculates me next Friday and next Sunday date.
The problem : the use of .toISOString uses UTC time. I need to change with something that outputs local time. I'm very new to javascript so I can't find the right property to use instead of .toIsostring.
What should I do ?
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
If you worry that the date is wrong in some timezones, try normalising the time
To NOT use toISO you can do this
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB',
{ year: 'numeric', month: '2-digit', day: '2-digit' })
.split("/")
function nextWeekdayDate(date, day_in_week) {
var ret = new Date(date || new Date());
ret.setHours(15, 0, 0, 0); // normalise
ret.setDate(ret.getDate() + (day_in_week - 1 - ret.getDay() + 7) % 7 + 1);
return ret;
}
let nextFriday = nextWeekdayDate(null, 5);
let followingSunday = nextWeekdayDate(nextFriday, 0);
console.log('Next Friday : ' + nextFriday.toDateString() +
'\nFollowing Sunday: ' + followingSunday.toDateString());
/* Previous code calculates next friday and next sunday dates */
var checkinf = nextWeekdayDate(null, 5);
var [yyyy, mm, dd] = nextFriday.toISOString().split('T')[0].split('-');
var checkouts = nextWeekdayDate(null, 7);
var [cyyy, cm, cd] = followingSunday.toISOString().split('T')[0].split('-');
console.log(yyyy, mm, dd)
// not using UTC:
const [dd1, mm1, yyyy1] = nextFriday.toLocaleString('en-GB', { year: 'numeric', month: '2-digit', day: '2-digit' }).split("/")
console.log(yyyy1, mm1, dd1)
You are concerned that the [yyyy,mm,dd] is in UTC and not in current timzone?
The nextFriday is a date object. Would it work if you use the get-functions instead?
e.g.
const nextFridayYear = nextFriday.getFullYear();
// get month is zero index based, i have added one
const nextFridayMonth = (nextFriday.getMonth() + 1).toString()
.padStart(2, '0');
const nextFridayDay = today.getDate().toString()
.padStart(2, '0');

Jquery - Return only the format dd/MM/YY HH:mm ,instead of returning time zone values, month name and etc [duplicate]

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

How to get date and time in Javascript not UTC

I am just trying to get date and time in the format below. It just seems very hard and complicated in JS.
2019-06-27 01:06:34.947
British time, date, hour minutes and seconds are the most important, milliseconds not essential.
Whenever I try, I get the time in UTC, I also do not need PM/AM etc shown.
var today = new Date().toLocaleDateString(undefined, {
day: '2-digit',
month: '2-digit',
year: 'numeric'
//hour: '2-digit',
//minute: '2-digit',
//second: '2-digit'
})
console.log('today', today)
var time = new Date().toLocaleTimeString(undefined, {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
})
console.log('time', time)
//var date = new Date();
//var timestamp = date.getTime();
var mytime = today + " " + time;
console.log('mytime', mytime)
//var tt = new Date().toLocaleString().replace(",","").replace(/:.. /," ");
var currentdate = new Date();
var datetime = currentdate.getDate() + "/" +
(currentdate.getMonth() + 1) + "/" +
currentdate.getFullYear() +
currentdate.getHours() + ":" +
currentdate.getMinutes() + ":" +
currentdate.getSeconds();
console.log('datetime', datetime)
X = new Date().toLocaleDateString();
Y = new Date().toLocaleTimeString('en-GB', {
hour: "numeric",
minute: "numeric"
});
mynew = X + " " + Y;
console.log('mynew', mynew)
I expect to see 2019-06-27 01:06:34.947 or 27-06-2019 01:06:34.947
I'd say your best option to format a local Date instance as YYYY-mm-DD HH:MM:SS would be to build the string yourself
const today = new Date()
const formatted =
`${
today.getFullYear()
}-${
String(today.getMonth()+1).padStart(2, '0')
}-${
String(today.getDay()).padStart(2, '0')
} ${
String(today.getHours()).padStart(2, '0')
}:${
String(today.getMinutes()).padStart(2, '0')
}:${
String(today.getSeconds()).padStart(2, '0')
}`
// this just displays it
document.querySelector('pre').textContent = formatted
<pre></pre>
Libraries like Moment.js make this sort of thing much easier.
moment().format('YYYY-MM-DD HH:mm:ss')
See https://momentjs.com/docs/#/displaying/

How do I split the date and time into two elements?

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)

Timestamp to human readable format

Well I have a strange problem while convert from unix timestamp to human representation using javascript
Here is timestamp
1301090400
This is my javascript
var date = new Date(timestamp * 1000);
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDay();
var hour = date.getHours();
var minute = date.getMinutes();
var seconds = date.getSeconds();
I expected results to be 2011 2, 25 22 00 00. But it is 2011, 2, 6, 0, 0, 0
What I miss ?
getDay() returns the day of the week. To get the date, use date.getDate(). getMonth() retrieves the month, but month is zero based, so using getMonth() + 1 should give you the right month. Time value seems to be ok here, albeit the hour is 23 here (GMT+1). If you want universal values, add UTC to the methods (e.g. date.getUTCFullYear(), date.getUTCHours())
const timestamp = 1301090400;
const date = new Date(timestamp * 1000);
const datevalues = [
date.getFullYear(),
date.getMonth()+1,
date.getDate(),
date.getHours(),
date.getMinutes(),
date.getSeconds(),
];
alert(datevalues); //=> [2011, 3, 25, 23, 0, 0]
Here is a small helper idea to retrieve values of a given Date:
const dateHelper = dateHelperFactory();
const formatMe = date => {
const vals = `yyyy,mm,dd,hh,mmi,ss,mms`.split(`,`);
const myDate = dateHelper(date).toArr(...vals);
return `${myDate.slice(0, 3).join(`/`)} ${
myDate.slice(3, 6).join(`:`)}.${
myDate.slice(-1)[0]}`;
};
// to a formatted date with zero padded values
console.log(formatMe(new Date(1301090400 * 1000)));
// the raw values
console.log(dateHelper(new Date(1301090400 * 1000)).values);
function dateHelperFactory() {
const padZero = (val, len = 2) => `${val}`.padStart(len, `0`);
const setValues = date => {
let vals = {
yyyy: date.getFullYear(),
m: date.getMonth()+1,
d: date.getDate(),
h: date.getHours(),
mi: date.getMinutes(),
s: date.getSeconds(),
ms: date.getMilliseconds(), };
Object.keys(vals).filter(k => k !== `yyyy`).forEach(k =>
vals[k[0]+k] = padZero(vals[k], k === `ms` && 3 || 2) );
return vals;
};
return date => ( {
values: setValues(date),
toArr(...items) { return items.map(i => this.values[i]); },
} );
}
.as-console-wrapper {
max-height: 100% !important;
}
Or see this small stackblitz project (a little bit more efficient).
var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();
Where unixtime is the time returned by your sql db. Here is a fiddle if it helps.
For example, using it for the current time:
document.write( new Date().toUTCString() );
here is kooilnc's answer w/ padded 0's
function getFormattedDate() {
var date = new Date();
var month = date.getMonth() + 1;
var day = date.getDate();
var hour = date.getHours();
var min = date.getMinutes();
var sec = date.getSeconds();
month = (month < 10 ? "0" : "") + month;
day = (day < 10 ? "0" : "") + day;
hour = (hour < 10 ? "0" : "") + hour;
min = (min < 10 ? "0" : "") + min;
sec = (sec < 10 ? "0" : "") + sec;
var str = date.getFullYear() + "-" + month + "-" + day + "_" + hour + ":" + min + ":" + sec;
/*alert(str);*/
return str;
}
use Date.prototype.toLocaleTimeString() as documented here
please note the locale example en-US in the url.
I was looking for a very specific solution for returning the current time as a guaranteed length string to prepend at the beginning of every log line. Here they are if someone else is looking for the same thing.
Basic Timestamp
"2021-05-26 06:46:33"
The following function returns a zero padded timestamp for the current time (always 19 characters long)
function getTimestamp () {
const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
const d = new Date();
return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
}
Full Timestamp
"2021-06-02 07:08:19.041"
The following function returns a zero padded timestamp for the current time including milliseconds (always 23 characters long)
function getFullTimestamp () {
const pad = (n,s=2) => (`${new Array(s).fill(0)}${n}`).slice(-s);
const d = new Date();
return `${pad(d.getFullYear(),4)}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}.${pad(d.getMilliseconds(),3)}`;
}
Hours, minutes and seconds depend on the time zone of your operating system. In GMT (UST) it's 22:00:00 but in different timezones it can be anything. So add the timezone offset to the time to create the GMT date:
var d = new Date();
date = new Date(timestamp*1000 + d.getTimezoneOffset() * 60000)
To direct get a readable local timezone:
var timestamp = 1301090400,
date = new Date(timestamp * 1000)
document.write( date.toLocaleString() );
I'm too late to the party since this question is already a decade old, but I want to provide a cleaner one without the use of any plugins like moment.js. only vanilla javascript.
export default {
// Accepts "1998-08-06 11:00:00" <-- This is UTC timestamp
getFormalDateTime(utcDate) {
const formattedUtc = utcDate.split(' ').join('T')+'Z'
let date = new Date(formattedUtc);
if (date.toString() === "Invalid Date")
return "N/A";
let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
let timeString = date.toLocaleTimeString("en-US", {hour: 'numeric', minute: 'numeric', hour12: true});
let formattedDate = dateString + " | " + timeString;
return formattedDate; // Returns "August 6, 1998 | 11:00 AM" <-- This is converted to client time zone.
},
// Accepts: "1998-08-06"
getFormalDate(convertDate) {
let date = new Date(convertDate);
if (date.toString() === "Invalid Date")
return "N/A";
let dateString = date.toLocaleDateString("en-US", {month: 'long', day: 'numeric', year: 'numeric'});
return dateString // Returns "August 6, 1998"
}
}
My code is formatted for ES6 modules because I use it as a module for my vuejs project but you can convert it to a normal javascript function.
getFormalDateTime('1998-08-06 11:00:00') the parameter should be in UTC time. This will return a formal date time converted to the client/browser timezone: August 6, 1998 | 11:00 AM
getFormalDate('1998-08-06') will just return August 6, 1998
More information here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Categories