Format date with datetime picker to DD-MM-YYYY - javascript

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

Related

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

How to format date and time in JavaScript based on

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,
});

How to add moment.locale() [duplicate]

This question already has answers here:
Locale detection with Moment.js
(3 answers)
Closed 2 years ago.
I have my moment date in English. I'm trying to add moment.locale to have my date in french but it doesn't work. should have created a variable to do that? Or just add moment.locale() somewhere ?
<View style={{flex: 1}}>
<Text style={{color: 'white', textAlign: 'center', marginTop:20}}>
{moment(element.dateMatch).format('LLLL')}
</Text>
</View>
with this code i have the date in english .
This is what I have at the top of the file where I initialize my locales
import moment from 'moment';
import 'moment/locale/fr';
import 'moment/locale/nl';
Each supported language should be explicitly included, as react-native bundles are completely built upfront.
A little bit further the locale can be activated by setting it to fr (or any other imported locale):
moment.locale('fr');
You need to do the following, import your locale on app initialisation or wherever you need it.
there is two methods one for older version and one for newer
// From 2.8.1 onward
moment.locale(String);
moment.locale(String[]);
moment.locale(String, Object);
// Deprecated in 2.8.1
moment.lang(String);
moment.lang(String[]);
moment.lang(String, Object);
then you need to import locales, related to your language. I will add an example for french language
moment.locale('fr', {
months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'),
monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'),
monthsParseExact : true,
weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'),
weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'),
weekdaysMin : 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'HH:mm',
LTS : 'HH:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D MMMM YYYY',
LLL : 'D MMMM YYYY HH:mm',
LLLL : 'dddd D MMMM YYYY HH:mm'
},
calendar : {
sameDay : '[Aujourd’hui à] LT',
nextDay : '[Demain à] LT',
nextWeek : 'dddd [à] LT',
lastDay : '[Hier à] LT',
lastWeek : 'dddd [dernier à] LT',
sameElse : 'L'
},
relativeTime : {
future : 'dans %s',
past : 'il y a %s',
s : 'quelques secondes',
m : 'une minute',
mm : '%d minutes',
h : 'une heure',
hh : '%d heures',
d : 'un jour',
dd : '%d jours',
M : 'un mois',
MM : '%d mois',
y : 'un an',
yy : '%d ans'
},
dayOfMonthOrdinalParse : /\d{1,2}(er|e)/,
ordinal : function (number) {
return number + (number === 1 ? 'er' : 'e');
},
meridiemParse : /PD|MD/,
isPM : function (input) {
return input.charAt(0) === 'M';
},
// In case the meridiem units are not separated around 12, then implement
// this function (look at locale/id.js for an example).
// meridiemHour : function (hour, meridiem) {
// return /* 0-23 hour, given meridiem token and hour 1-12 */ ;
// },
meridiem : function (hours, minutes, isLower) {
return hours < 12 ? 'PD' : 'MD';
},
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // Used to determine first week of the year.
}
});
And then you can just use any function you want. Also you can switch between default en and just defined fr locale.
moment.locale('fr');
moment(1316116057189).fromNow(); // il y a une heure
moment.locale('en');
moment(1316116057189).fromNow(); // an hour ago
original docs
You don't necessary need to use moment for this.
You can use the toLocaleDateString from the Date function in js.
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
console.log(element.dateMatch.toLocaleDateString('fr-FR', options));
// example output: jeudi 20 décembre 2012

My Date Picker always open in the current month

I'm using a my-date-range-picker to display a calendar to the user choose a date and display her in a span like a string.
Step by step:
I click in the label to open the calendar;
The calendar opens with current date selected;
I choose a date, for example, 8th October, 2018;
The calendar closes;
The date that i previous choose appears correctly in span;
Open the calendar again;
Here, the calendar shows the current month(September). I want that calendar show the date that i previous select - 8th October, 2018;
My HTML code for date picker:
<my-date-range-picker *ngIf="this.opened && view=='date'" class="date_picker" [options]="date_picker" [(ngModel)]="this.model" (dateSelected)="onDateRangeChanged($event)"></my-date-range-picker>
The label responsable to show the selected date:
<div class="lineheight" [ngClass]="{'dates': type_resume_view == 'none'}">
<span>{{dates.first.format('DD/MM/YYYY')}}</span>
</div>
In my TS file, the event of date change goes to:
onDateRangeChanged(ev) {
if (this.view == "range") {
this.dates.first = moment({
day: ev.beginDate.day,
month: ev.beginDate.month - 1,
year: ev.beginDate.year
});
this.dates.last = moment({
day: ev.endDate.day,
month: ev.endDate.month - 1,
year: ev.endDate.year
});
this.setDate();
if (!this.always_open) {
this.onSelectDate.emit(this.dates);
this.opened = false;
}
}
if (this.view == "date") {
this.dates.first = moment({
day: ev.date.day,
month: ev.date.month - 1,
year: ev.date.year
});
this.dates.last = moment({
day: ev.date.day,
month: ev.date.month - 1,
year: ev.date.year
});
if (!this.always_open) {
this.onSelectDate.emit(this.dates);
this.opened = false;
}
if (this.interval != undefined) {
switch (this.interval) {
case "week":
this.dates.first = this.dates.first.startOf("week").add(1, 'day');
this.dates.last = this.dates.last.endOf("week").add(1, 'day');
break;
case "month":
this.dates.first = this.dates.first.startOf("month");
this.dates.last = this.dates.last.endOf("month");
break;
}
}
this.setDate();
if (this.always_open) {
this.opened = false;
setTimeout(() => {
this.opened = true
}, 0);
}
}
}
And then to method setDate():
this.model.beginDate.year = this.dates.first.format("YYYY");
this.model.beginDate.month = this.dates.first.format("MM");
this.model.beginDate.day = this.dates.first.format("DD");
this.model.endDate.year = this.dates.last.format("YYYY");
this.model.endDate.month = this.dates.last.format("MM");
this.model.endDate.day = this.dates.last.format("DD");
My declared variables are:
date_picker: IMyDrpOptions = {
showClearBtn: false,
showApplyBtn: false,
showSelectDateText: false,
componentDisabled: false,
markCurrentDay: true,
showWeekNumbers: true,
inline: true,
dateFormat: 'yyyy-mm-dd',
firstDayOfWeek: 'mo',
disableUntil: {
year: 1990,
month: 1,
day: 1
}
};
private model: any = {
beginDate: {
year: 2018,
month: 10,
day: 9
},
endDate: {
year: 2018,
month: 10,
day: 19
}
};
Auxiliar Methods:
open_calendar() {
this.model = this.model;
if (!this.always_open) {
this.opened = !this.opened;
if (this.opened) {
this.onCalendarOpen.emit(this.dates);
} else {
this.onClose.emit();
}
}
}
close_calendar() {
this.opened = false;
this.onClose.emit();
}
I just want that calendar open in the previous selected month, because the date is correctly selected.
UPDATE:
The example that i describe, the date is correct but not show the month correctly
my-date-range-picker has the defaultMonth attribute, that's what you will use to set which month the calendar should open such as:
import { IMyDefaultMonth } from 'mydatepicker';
private defaultMonth: IMyDefaultMonth = { defMonth: '12/2019' };
In HTML:
<my-date-range-picker name="mydate" [options]="myDatePickerOptions" [defaultMonth]="defaultMonth" />
in the example the default month will open at December 2019 as defined by defaultMonth.

How convert world clock format with dropdown menu or button (12/24hour)?

How to change the time format of the script results below with the drop down menu? Thanks.
function show()
{
var time=new Date()
document.write("London " + time.toLocaleTimeString("en-US", { timeZone: "Europe/London", hour: "2-digit", minute:"2-digit" })+ "<br>");
document.write("Paris " + time.toLocaleTimeString("en-US", { timeZone: "Europe/Paris", hour: "2-digit", minute:"2-digit" })+ "<br>");
document.write("Tokyo " + time.toLocaleTimeString("en-US", { timeZone: "Asia/Tokyo", hour: "2-digit", minute:"2-digit" }));
}
show();
//Output
// London : time
// Paris : time
// Tokyo : time
<p>Format :
<select name="select" id="select">
<option value="12">AM/PM</option>
<option value="24">24 Hours</option>
</select>
</p>
You can add hour12: false, to your existing code when 24 Hours option is selected. Sample below, check for else condition for the change.
function show(format) {
var time = new Date();
var str = "";
if (format === "12") {
str += "London " + time.toLocaleTimeString("en-US", { timeZone: "Europe/London", hour: "2-digit", minute: "2-digit" }) + "<br>";
str += "Paris " + time.toLocaleTimeString("en-US", { timeZone: "Europe/Paris", hour: "2-digit", minute: "2-digit" }) + "<br>";
str += "Tokyo " + time.toLocaleTimeString("en-US", { timeZone: "Asia/Tokyo", hour: "2-digit", minute: "2-digit" });
}
else {
str += "London " + time.toLocaleTimeString("en-US", { timeZone: "Europe/London", hour12: false, hour: "2-digit", minute: "2-digit" }) + "<br>";
str += "Paris " + time.toLocaleTimeString("en-US", { timeZone: "Europe/Paris", hour12: false, hour: "2-digit", minute: "2-digit" }) + "<br>";
str += "Tokyo " + time.toLocaleTimeString("en-US", { timeZone: "Asia/Tokyo", hour12: false, hour: "2-digit", minute: "2-digit" });
}
document.getElementById("displayTime").innerHTML = str;
}
window.onload = function() { show("12") };
<p>Format :
<select name="select" id="select" onchange="show(this.value)">
<option value="12">AM/PM</option>
<option value="24">24 Hours</option>
</select>
</p>
<div id="displayTime"></div>

Categories