问题
I receive a date from an object in a loop in this format : 2018-08-06 20:45:00
And I want to display only "20:45" (always with two digits for minutes) in the Timezone of the client. I have created this method in the methods part of vue.js :
ihaveadate(dateFromLoop) {
var d = new Date(dateFromLoop);
d.setTime(d.getTime() + new Date().getTimezoneOffset() * 60 * 1000);
var hour = d.getUTCHours();
var minutes = (d.getMinutes() < 10 ? "0" : "") + d.getMinutes();
return `${hour}:${minutes}`;
}
It seemed to work fine except that on safari I have NaN:NaN, is there a clean solution to this problem ?
After reading ur answers i made it works like that :
var dateFromLoop = '2018-08-06 20:45:00';
var date = Date.parse(dateFromLoop.replace(" ", "T"));
const daty = new Intl.DateTimeFormat({
hour: "numeric",
minute: "numeric"
}).format(date);
console.log(daty);
回答1:
yes, this will not work on safari, as for ECMAScript 5 ISO-8601 format support:
Alternatively, the date/time string may be in ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed.
you need to include T withing the date time in order to make it work on Safari:
new Date('2014-02-18T15:00:48');
you can try and do it like this:
new Date(dateFromLoop.replace(/\s/, 'T');
回答2:
For a clean solution There is a library called moment by using that you can do all your time and date manipulation
for your problem in Moment
const d = new Date(yourDate);
const hourAndMin = moment().format('h:mm');
Refer Moment
回答3:
You can use Vanilla for this.
docs for parse
docs for format
The example direct from the source
var date = Date.parse('2018-08-06 20:45:00'.replace(' ', 'T'));
// toLocaleString without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(new Intl.DateTimeFormat({
hour: 'numeric',
minute: 'numeric'
}).format(date));
来源:https://stackoverflow.com/questions/51708032/display-hours-and-minutes-works-on-all-browsers-except-safari-javascript-date