Skip to content

Commit 8516151

Browse files
committed
Core: Calendar - fix issue with double replacing, add time tokens
Fixes #3434 Fixes #3439
1 parent f69a955 commit 8516151

File tree

1 file changed

+46
-15
lines changed

1 file changed

+46
-15
lines changed

src/core/components/calendar/calendar-class.js

Lines changed: 46 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -493,22 +493,53 @@ class Calendar extends Framework7Class {
493493
const weekDay = date.getDay();
494494
const { monthNames, monthNamesShort, dayNames, dayNamesShort } = calendar;
495495
const { dateFormat, locale } = calendar.params;
496+
497+
function twoDigits(number) {
498+
return (number < 10) ? `0${number}` : number;
499+
}
496500
if (typeof dateFormat === 'string') {
497-
return dateFormat
498-
.replace(/yyyy/g, year)
499-
.replace(/yy/g, String(year).substring(2))
500-
.replace(/mm/g, month1 < 10 ? `0${month1}` : month1)
501-
.replace(/m(\W+)/g, `${month1}$1`)
502-
.replace(/(\W+)m/g, `$1${month1}`)
503-
.replace(/MM/g, monthNames[month])
504-
.replace(/M(\W+)/g, `${monthNamesShort[month]}$1`)
505-
.replace(/(\W+)M/g, `$1${monthNamesShort[month]}`)
506-
.replace(/dd/g, day < 10 ? `0${day}` : day)
507-
.replace(/d(\W+)/g, `${day}$1`)
508-
.replace(/(\W+)d/g, `$1${day}`)
509-
.replace(/DD/g, dayNames[weekDay])
510-
.replace(/D(\W+)/g, `${dayNamesShort[weekDay]}$1`)
511-
.replace(/(\W+)D/g, `$1${dayNamesShort[weekDay]}`);
501+
const tokens = {
502+
yyyy: year,
503+
yy: String(year).substring(2),
504+
mm: twoDigits(month1),
505+
m: month1,
506+
MM: monthNames[month],
507+
M: monthNamesShort[month],
508+
dd: twoDigits(day),
509+
d: day,
510+
DD: dayNames[weekDay],
511+
D: dayNamesShort[weekDay],
512+
};
513+
if (calendar.params.timePicker) {
514+
const hours = date.getHours();
515+
const minutes = date.getMinutes();
516+
const seconds = date.getSeconds();
517+
let hours12 = hours;
518+
if (hours > 12) hours12 = hours - 12;
519+
if (hours === 0) hours12 = 12;
520+
const a = hours >= 12 && hours !== 0 ? 'pm' : 'am';
521+
522+
Object.assign(tokens, {
523+
HH: twoDigits(hours),
524+
H: hours,
525+
hh: twoDigits(hours12),
526+
h: hours12,
527+
ss: twoDigits(seconds),
528+
s: seconds,
529+
':mm': twoDigits(minutes),
530+
':m': minutes,
531+
a,
532+
A: a.toUpperCase(),
533+
});
534+
}
535+
const regexp = new RegExp(
536+
Object.keys(tokens).map(t => `(${t})`).join('|'),
537+
'g',
538+
);
539+
return dateFormat.replace(regexp, (token) => {
540+
if (token in tokens) return tokens[token];
541+
return token;
542+
});
512543
}
513544
if (typeof dateFormat === 'function') {
514545
return dateFormat(date);

0 commit comments

Comments
 (0)