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/
Related
I want to convert string date 2020-06-21T10:15:00Z into 21-06-2020 10:15?
I did it like splitting on two parts and remove last 4 characters from the time:
const newDate = date.split('T');
const time = newDate.length >= 1 ? newDate[1].slice(3, -1) : '';
I am looking for some better solution?
Since your input string has all the necessary parts, you may break it into pieces (e.g. using String.prototype.split()) and build up anew in desired order and with necessary delimiters:
const dateStr = '2020-06-21T10:15:00Z',
[yyyy,mm,dd,hh,mi] = dateStr.split(/[/:\-T]/)
console.log(`${dd}-${mm}-${yyyy} ${hh}:${mi}`)
.as-console-wrapper{min-height:100%;}
You can format a
const str = "2020-06-21T10:15:00Z";
const date = new Date(str);
var options = {year: 'numeric', month: 'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric'};
console.log(date.toLocaleDateString('UTC', options));
date string using toLocaleDateString.
Try this :
<script>
function myFunction() {
var oldDate = Date.parse("2020-06-21T10:15:00Z");
var newDate = formatDate(new Date(d));
console.log(newDate)
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
hour = d.getHours();
minutes = d.getMinutes();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-') + " " + [hour,minutes].join(":");
}
</script>
try this :)
document.getElementById(' ').innerHTML = datum.toLocaleString('de-DE');
You can use the dateFormat
const mydate = new Date("2020-06-21T10:15:00Z");
console.log(dateFormat(mydate, "dd-mm-yyyy hh:MM"));
Curently i am working in GMT+0530 timezone
new Date()
Fri Mar 06 2020 11:29:12 GMT+0530 (India Standard Time)
Now i am trying to format it as i need
var today = new Date();
var date = today.toLocaleString('default', { weekday: 'short' })+' '+today.toLocaleString('default', { month: 'short' })+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time+' '+today.getFullYear();
Time is stored as follows
Fri Mar-6 11:22:4 2020
Now how to get the UTC time in the same format
You can get the offset between your timezone and UTC, then create a new Date with the added offset and format it as you did previously.
var localToday = new Date();
var offset = localToday.getTimezoneOffset();
var today = new Date(localToday.getTime() + (offset * 60 * 1000));
var date = today.toLocaleString('default', { weekday: 'short' })+' '+today.toLocaleString('default', { month: 'short' })+'-'+today.getDate();
var time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
var dateTime = date+' '+time+' '+today.getFullYear();
console.log(dateTime);
Since you're using toLocaleString with options, just specify the timezone as UTC and also use UTC methods for the day and time, e.g.
var today = new Date();
var date = today.toLocaleString('default', {weekday: 'short', timeZone:'UTC'}) + ' ' +
today.toLocaleString('default', {month: 'short', timeZone:'UTC'}) + '-' +
today.toLocaleString('default', {day: '2-digit', timeZone:'UTC'});
// var time = today.getUTCHours() + ":" + today.getUTCMinutes() + ":" + today.getUTCSeconds();
var time = today.toLocaleString('default',{hour:'2-digit',minute:'2-digit', second:'2-digit', hour12:false, timeZone:'UTC'});
var year = today.toLocaleString('default',{year:'numeric', timeZone:'UTC'});
var dateTime = date + ' ' + time + ' ' + year;
console.log(dateTime);
Try using moment-js. It has got wide variety of flags to format the way you want.
Working sandbox:
https://codesandbox.io/s/xenodochial-cdn-yp5mb
const moment = require("moment");
console.log(moment.utc().format('ddd MMM-D YYYY HH:mm:ss'));
This behavior doesn't occur when using locale "en-US".
Also, whether hour is set to "2-digit" or "numeric",
the output remains the same for both "ja-JP" and "en-US" locales.
Is this a bug? Is there a workaround to show the hour in 2-digits in this format?
yyyy/MM/dd HH:mm:ss
function showDate() {
var date = new Date('2019-05-22T00:37:36.37Z');
var options = { year: 'numeric', day: '2-digit', month: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false };
document.querySelector("#ja-jp").innerHTML = date.toLocaleString('ja-JP', options);
document.querySelector("#en-us").innerHTML = date.toLocaleString('en-US', options);
}
window.onload = showDate;
<div id="ja-jp"></div>
<div id="en-us"></div>
Not sure if this can help you, but have a look at http://phrogz.net/JS/FormatDateTime_JS.txt
A very nice way to format dates in JS.
I don't really like this workaround so I'm not going to accept this as the answer.
But since it works, I'm just gonna put it here.
function formatDate(date) {
var year = date.getFullYear();
var month = ("0" + (date.getMonth() + 1)).slice(-2);
var day = ("0" + date.getDate()).slice(-2);
var hour = ("0" + date.getHours()).slice(-2);
var minute = ("0" + date.getMinutes()).slice(-2);
var second = ("0" + date.getSeconds()).slice(-2);
return year + "/" + month + "/" + day + " " + hour + ":" + minute + ":" + second;
}
Reference link.
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 have this code but it displays first 3 letters of month in english. How can I change it to spanish?
if (secondsPast > 86400) {
var date = new Date(timestamp);
var currentDate = new Date(now);
var day = date.getDate();
var month = date.toDateString().match(/ [a-zA-Z]*/)[0].replace(' ', '');
var year = date.getFullYear() == currentDate.getFullYear() ? '' : ', ' + date.getFullYear();
return month + ' ' + day + ' ' + year;
}
You can use toLocaleDateString().
The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date.
Please read more about it at moz wiki
Example:
var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(event.toLocaleDateString('es-ES', options));
In PHP:
From the DateTime format page:
This method does not use locales. All output is in English.
If you need locales look into strftime Example:
setlocale(LC_ALL,"es_ES");
$string = "24/11/2014";
$date = DateTime::createFromFormat("d/m/Y", $string);
echo strftime("%A",$date->getTimestamp());