How to format date and time in JavaScript based on - javascript

What is the best and a clean way for me to format date and time string in following format?
For today:
HH:MM PM/AM
For any time not today:
MM(short string) DD(short string) HH:MM PM/AM
const displayTime = new Date(Date.now()).toLocaleDateString('en-US', {
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: true,
});
console.log(displayTime) //=>"May 18, 5:18 PM"
//expected 4:26 PM for today
//expected MAY 1ST(2ND, 3RD, 4TH) 4:26 PM for any day not today

You're on the right track with toLocaleDateString, but it can't do one format for today and one for older on it's own - you'll have to roll that yourself as there is some implicit logic - do you mean this day or in the last 24 hours? Do you handle timezones? How should future times be handled? And so on.
Assuming you mean today this would be:
const d = dateIWantToFormat;
// Is this date today?
const today = d.toDateString() === new Date().toDateString();
const displayTime = d.toLocaleDateString(
'en-US',
today ? { // If today just show "HH:MM PM/AM"
hour: 'numeric',
minute: 'numeric',
hour12: true,
} :
{ // Otherwise show "mmm DD HH:MM PM/AM"
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: true,
});

Related

toLocaleDateString on Android returns wrong format

I use toLocaleDateString to get different date formats for different countries.
But on Android then I pass, for example, 'fr-FR' or 'en-GB', it returns 'mm-dd-yyy' format instead of 'dd-mm-yyyy'. On iOS and desktop it works correct.
Here is my code:
const options = {
year: 'numeric',
month: '2-digit',
day: '2-digit',
timeZone: 'UTC',
timeZoneName: 'short'
};
const localeDate = new Date("2022-09-23").toLocaleDateString('fr-FR', options);
console.log(localeDate)

intl date format is not formatting data as expected nodeJS

I have this format options
const dateTimeFormat = new Intl.DateTimeFormat("default", {
year: "numeric",
month: "numeric",
day: "numeric",
});
when I do dateTimeFormat.format(new Date()) it return 3.9.2021 instead of 3/9/2021 as it is formatted in the docs
how can I fix this and why is this happening

Format date with datetime picker to DD-MM-YYYY

I am using DateTime picker from material.
But I want to have the format like this:
2021-02-15 23:59:59
So I try it like this:
export const MY_DATE_FORMATS = {
parse: {
dateInput: 'YYYY-MM-DD',
},
display: {
dateInput: 'MMM DD, YYYY',
monthYearLabel: 'MMMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY'
},
};
#Component({
selector: 'app-widget-editor',
templateUrl: './widget-editor.component.html',
styleUrls: ['./widget-editor.component.css'],
providers: [{provide: DateAdapter, useClass: AppDateAdapter},
{provide: MAT_DATE_FORMATS, useValue: MY_DATE_FORMATS}]
})
and template looks like this:
<div class="form-group row">
<label for="start" class="editor-label col-sm-4"><strong> Time start:</strong></label>
<input [(ngModel)]="start" [ngModelOptions]="{standalone: true}" type="text" class="date" id="start" value="start" matInput [ngxMatDatetimePicker]="picker">
<ngx-mat-datetime-picker #picker></ngx-mat-datetime-picker>
<span class="ml-2" (click)= "reOpenCalender()">
<fa-icon [icon]="faCalendarAlt" size="1x" #picker [styles]="{'color': '#B7B7B7'}"
></fa-icon>
</span>
</div>
But this doesn't work, it still shows this:
2/25/2021, 16:32:52
So what I have to change?
I try it like this:
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
if (displayFormat === 'input') {
let day: string = date.getDate().toString();
day = +day < 10 ? '0' + day : day;
let month: string = (date.getMonth() + 1).toString();
month = +month < 10 ? '0' + month : month;
let year = date.getFullYear();
return `${year}-${month}-${day}`;
}
return date.toDateString();
}
}
export const APP_DATE_FORMATS: MatDateFormats = {
parse: {
dateInput: { month: 'short', year: 'numeric', day: 'numeric' },
},
display: {
dateInput: 'input',
monthYearLabel: { year: 'numeric', month: 'numeric' },
dateA11yLabel: { year: 'numeric', month: 'long', day: 'numeric'
},
monthYearA11yLabel: { year: 'numeric', month: 'long' },
}
};
But I don't use a date picker, But I am using: DateTime picker:
https://stackblitz.com/edit/demo-ngx-mat-datetime-picker?file=src%2Fapp%2Fapp.module.ts
and then it doesn't work.
You could make it yourself by putting together the day, month, and year. I'm not sure if this code is exactly what you want but you could do something similar.
var today = new Date();
var date = today.getDate() + "/" + (today.getMonth() + 1) + "/" + today.getFullYear();
Use thisone for your date format.
DateFormat :- this.currentDate = ${this.currDate.getFullYear().toString().padStart(4, '0')}-${(this.currDate.getMonth() + 1).toString().padStart(2, '0')}-${this.currDate.getDate().toString().padStart(2, '0')} ${this.currDate.getHours().toString().padStart(2, '0')}:${this.currDate.getMinutes().toString().padStart(2, '0')}:${this.currDate.getSeconds().toString().padStart(2, '0')}

Convert TimeZone Time string correctly into Local Time

I am trying to convert a time string returned from our backend system but I am unable to get the correct local time.
Time string returned from backend: "2020-08-28T07:00:00.000Z"
Expected local time needed: Aug 28, 2020 12:00 AM
I tried:
converting it with Moment.js Failed:
moment(backendTime).format(
"MMM D,YYYY h:mm a"
)
Somehow I got "Jan 1st 20 12:00 AM", I don't understand it at all
converting it by casting to Date Failed as well:
Date("2020-08-28T07:00:00.000Z")
Ended up getting: " Mon Sep 21 2020 00:07:29 GMT-0700 (Pacific Daylight Time) "
I am running out of ideas right now, I feel it shouldn't be this difficult but just cannot get it.
The format you are getting is exactly what you have requested.
To get the output you desire using moment.js you need to use the following format:
moment(backendTime).format("MMM DD, YYYY hh:mm A");
You can test it here: https://jsfiddle.net/oz6mx3nh/
In vanilla JS you can use the DateTimeFormat to format your dates based on a timezone. All the options for DateTimeFormat are documented here.
The different options for the locale (en-US) is listed here
Here is a full list of all the time zones.
See bottom snippet for the output of each locale (in the provided list)
const date = new Date("2020-08-28T07:00:00.000Z");
const format = new Intl.DateTimeFormat(
"en-US",
{
month: "short",
day: "2-digit",
year: "numeric",
hour: "2-digit",
hour12: true,
minute: "2-digit",
timeZone: "America/New_York",
}
).format(date)
console.log(format);
A list of outputs from every locale:
const date = new Date("2020-08-28T07:00:00.000Z");
const locales = ["ar-SA", "bn-BD", "bn-IN", "cs-CZ", "da-DK", "de-AT", "de-CH", "de-DE", "el-GR", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", "en-NZ", "en-US", "en-ZA", "es-AR", "es-CL", "es-CO", "es-ES", "es-MX", "es-US", "fi-FI", "fr-BE", "fr-CA", "fr-CH", "fr-FR", "he-IL", "hi-IN", "hu-HU", "id-ID", "it-CH", "it-IT", "jp-JP", "ko-KR", "nl-BE", "nl-NL", "no-NO", "pl-PL", "pt-BR", "pt-PT", "ro-RO", "ru-RU", "sk-SK", "sv-SE", "ta-IN", "ta-LK", "th-TH", "tr-TR", "zh-CN", "zh-HK", "zh-TW"];
const formatDate = (locale, date) => new Intl.DateTimeFormat(
locale,
{
month: "short",
day: "2-digit",
year: "numeric",
hour: "2-digit",
hour12: true,
minute: "2-digit",
timeZone: "America/New_York",
}
).format(date);
// Loop over each locale
for(const locale of locales) {
const formatted = formatDate(locale, date);
console.log(`${locale}: ${formatted}`);
}
A few things:
Assuming your computer is set for Pacific time, then:
moment("2020-08-28T07:00:00.000Z").format("MMM D, YYYY h:mm a")
//=> "Aug 28, 2020 12:00 am"
That will indeed return the value you expected. You said you got "Jan 1st 20 12:00 AM", but that is not possible, as neither the values nor the format matches.
When you tried the Date object, you got the result you did because you omitted the new keyword (see this explanation). It should instead be:
new Date("2020-08-28T07:00:00.000Z")
Keep in mind that this produces a Date object. If you log that object directly, the result is implementation specific. It may vary across browsers. Instead, you should call a function such as toString or toLocaleString from it.
If this is a new project, you should probably avoid using Moment. Please read https://momentjs.com/docs/#/-project-status/

Intl.DateTimeFormat shows time being 24:59

Hey everyone| just checking if I am doing something wrong. The code below gives me time = 24:59, in Prague (GMT+1). Using Chrome.
new Intl.DateTimeFormat(
'en',
{
weekday: 'long',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hour12: false
}
).format(new Date('2020-03-11T23:59:00Z')
)
// "Thursday, March 12, 24:59"
When using the .getHours() I will get a correct value of 0 though.
new Date('2020-03-11T23:59:00Z'); // Thu Mar 12 2020 00:59:00 GMT+0100 (Central European Standard Time)
new Date('2020-03-11T23:59:00Z').getHours(); // 0
Thanks for suggestions, I didn't found any related issues about this.
Tomas
Your code gives me "Thursday, March 12, 00:59" in Firefox and "Thursday, March 12, 24:59" in Chrome (80.0.3987.149)
There appears to be a bug open for Chrome 80 https://support.google.com/chrome/thread/29828561?hl=en, open since February, but not much is said about whether it will be fixed and how. Consider upvoting it.
According to a comment posted there, you could work around the issue by replacing the hour12 property with hourCycle: 'h23'.
new Intl.DateTimeFormat(
'en',
{
weekday: 'long',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
hourCycle: 'h23'
}
).format(new Date('2020-03-11T23:59:00Z')
)
// "Thursday, March 12, 00:59"
This seems to do the trick for me
The issue seems to be the default setting for HourCycle and langauge en, which you'd expect to be h23, but Chrome is using h24. You can fix it as described by toniedzwiedz, or you can provide a suitable country code for the language tag to force the HourCycle to default to h23, say GB:
let d = new Date(2020,2,1,0,23);
let opts = { hour12: false, hour: 'numeric' };
console.log(d.toLocaleString('en', opts)); // 24 (Chrome), 00 others
console.log(d.toLocaleString('en-GB', opts)); // 00 all

Categories