Issue
Cannot add formatting for time. Should be displayed in 12 hours, AM PM format; I need this one for a subscription form for customers. The Date and Time I am using for schedule
How to get 12 hours AM PM time format?
private weekday = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
private monthNames = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'
];
constructor(private router: Router) {}
ngOnInit() {
}
getCurrentUrl() {
return this.router.url.split('#')[0];
}
formatDate(dt) {
const _date = new Date(dt);
const nameDay = this.weekday[_date.getDay()];
return nameDay + ', ' + _date.getDate() + ' ' + this.monthNames[_date.getMonth()] + ' ' + _date.getFullYear();
}
getTime(dt) {
const _date = new Date(dt);
let _hour = _date.getHours().toString();
let _min = _date.getMinutes().toString();
_hour = _hour.length === 1 ? '0' + _hour.toString() : _hour;
_min = _min.length === 1 ? '0' + _min.toString() : _min;
return _hour + ':' + _min;
Solution
I feel like I need more detail. But given what you have provided:
https://codepen.io/nstanard/pen/bzbdrJ
let date = new Date();
function formatDate(dt) {
// const _date = new Date(dt);
// const nameDay = this.weekday[dt.getDay()];
// return nameDay + ', ' + dt.getDate() + ' ' + this.monthNames[dt.getMonth()] + ' ' + dt.getFullYear();
let normalizeHour = dt.getHours() >= 13 ? dt.getHours() - 12 : dt.getHours()
return dt.getHours() >= 13 ? normalizeHour + 'PM' : normalizeHour + 'AM'
}
console.log(formatDate(date))
Here is the hour of a date object formatted for AM and PM.
Read more
However, if you are using TypeScript and Angular I suggest you take a look a the following example: https://stackblitz.com/edit/angular-sc1ihu
create a date object
dateNow : Date = new Date();
Use the date format in the html.
{{dateNow | date:'short'}}
Using DatePipe is part of ng.common and IS best practice.
Answered By - nstanard
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.