How to add moment.locale() [duplicate] - javascript

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

Related

How to use a date/time "preset" from the current locale in date-fns format function?

I'm setting the default locale for date-fns this way:
import { it } from 'date-fns/locale';
import { setDefaultOptions } from 'date-fns';
setDefaultOptions ({ locale: it });
And this is working good for methods like formatDistance or formatRelative:
formatDistanceToNow(new Date(2014, 6, 2), { addSuffix: true}); // "8 anni fa"
With the "raw" format function you are forced to specify a format (second argument). Is there any way to use a "preset" for the current locale?
// The format function force you to specify the format
format(new Date(2017, 10, 6), 'dd/MM/y HH:mm'); // 06/11/2017 00:00
For example, italian language specify these presets (source code) but it's not exporting them:
const dateFormats = {
full: 'EEEE d MMMM y',
long: 'd MMMM y',
medium: 'd MMM y',
short: 'dd/MM/y',
}
const timeFormats = {
full: 'HH:mm:ss zzzz',
long: 'HH:mm:ss z',
medium: 'HH:mm:ss',
short: 'HH:mm',
}
How to pass the short date/time formats to format, instead of passing "dd/MM/y HH:mm" all the time?

With Moment.js - what is the best way to display a duration with modified locale data alongside a duration with default locale data?

Essentially I need to display:
"Runs every minute"
which has modified locale data to use "minute" instead of "a minute"
AND
"Will run again in a minute"
which has default locale data, in the same Component.
The updated locale I need:
moment.updateLocale('en', {
relativeTime: {
future: 'in %s',
past: '%s ago',
s: 'few seconds',
ss: '%d seconds',
m: 'minute',
mm: '%d minutes',
h: 'hour',
hh: '%d hours',
d: 'day',
dd: '%d days',
M: 'month',
MM: '%d months',
y: 'year',
yy: '%d years'
}
});
What I think I know:
moment.duration only supports language locale updates and does not have access to the full locale object. So I can't update locale like moment.duration.locale('en', localeUpdates).
A moment() instance does not have access to .duration. So I can't say
const mod = moment();
mod.updateLocale('en', localeUpdates);
mod.duration(timestamp);
As a result
Any attempt to display BOTH of the durations above fail, because the only way to update duration locale is globally.
Is there a way forward here that doesn't involve regex?
Sandbox: https://codesandbox.io/s/momentjs-ejmb6?file=/src/index.js
After doing some more digging I found you can create a custom locale, which Duration can then use.
More info here https://momentjs.com/docs/#/customization/
So you would define your custom locale like
import moment from 'moment';
moment.defineLocale('en-modified', {
parentLocale: 'en',
relativeTime: {
future: 'in %s',
past: '%s ago',
s: 'few seconds',
ss: '%ds',
m: '%dm',
mm: '%dm',
h: '%dhr',
hh: '%dhr',
d: '%dd',
dd: '%dd',
M: '%dmo',
MM: '%dmo',
y: '%dyr',
yy: '%dyr'
}
});
export default moment;
And then use it like
moment.duration.locale('en-modified')
Unfortunately locale and humanize() function doesn't solve everything and you have to create custom format function. As a another workaround moment().duration().valueOf() returns ISO 8601 duration so you can find api which processes that to human readable format or again create one.
const format = (momentObject, options) => {
let text = momentObject.humanize();
if (!options) {
return text;
}
if (!options.withDeterminer) {
if (momentObject === "PT1M") {
return "minute"
}
return text.replace(/a\s/g, '');
}
}
const result1 = format(moment.duration(1, "minutes"), {
withDeterminer: false
});
const result2 = format(moment.duration(1, "minutes"));
console.log(result1)
console.log(result2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

Is there any way to shorten the Livestamp.js time from '10 minutes ago' to '10m ago'?

It could be achieved by editing the defaultRelativeTime variable in the moment.js file from this:
var defaultRelativeTime = {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
m : 'a minute',
mm : '%d minutes',
h : 'an hour',
hh : '%d hours',
d : 'a day',
dd : '%d days',
M : 'a month',
MM : '%d months',
y : 'a year',
yy : '%d years'
};
To this:
var defaultRelativeTime = {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
m : '1m',
mm : '%dm',
h : '1h',
hh : '%dh',
d : '1D',
dd : '%dD',
M : '1M',
MM : '%dM',
y : '1Y',
yy : '%dY'
};
But is there any other way in which it could be done WITHOUT modifying the moment.js file?
You can customize the relative time format for your locale using updateLocale function. You need to pass the relative time object to it.
In your case:
moment.updateLocale('en', {
relativeTime : {
future : 'in %s',
past : '%s ago',
s : 'a few seconds',
m : '1m',
mm : '%dm',
h : '1h',
hh : '%dh',
d : '1D',
dd : '%dD',
M : '1M',
MM : '%dM',
y : '1Y',
yy : '%dY'
}});

Why when I call gotoDate of fullCalender, it only increments day by day?

I want fullCalendar to go to one a specifical day, but when I call
$('#calendarContainer').fullCalendar('gotoDate', date);
It only increment the view of the actual date by one.
My variable date is
var date =$.fullCalendar.moment(moment.utc(app.mCurrentStartDate).format('YYYY-MM-DD'));
My only way to make it work was to do
for (var i = 0; i < 100; i++)
{
$('#calendarContainer').fullCalendar('gotoDate', date);
}
But that is not possible.
My calendar use custom views
views: {
agendaThreeDay: {
type: 'agenda',
duration: { days: 3 },
buttonText: '3 day',
columnFormat: 'dddd D MMMM',
},
agendaTwoDay: {
type: 'agenda',
duration: { days: 2 },
buttonText: '2 day',
columnFormat: 'dddd D MMMM',
}
},
Do you know if this is the intented behaviour of gotoDate, or may be I use it the wrong way ?
Thanks.

How to set start time?

I was trying to set start time using xdsoft dateTimePicker. I just want to see 00:00 time when I open picker at first time, but I've got a current time. As documentation says, all I have to do is set startTime : "my time", but I have no effect. Also example of startDate doesn't work.
My code:
<script type="text/javascript">
jQuery(
"#<c:out value="${requestItem.fieldNumber}"/>")
.datetimepicker(
{
lang : 'ru',
i18n : {
ru : {
months : [
'Январь',
'Февраль',
'Март',
'Апрель',
'Май',
'Июнь',
'Июль',
'Август',
'Сентябрь',
'Октябрь',
'Ноябрь',
'Декабрь', ],
dayOfWeek : [
"Вс",
"Пн",
"Вт",
"Ср",
"Чт",
"Пт",
"Сб", ]
}
},
startDate:'1987/12/03',
dayOfWeekStart : 1,
timepicker : true,
format : 'd.m.Y H:i'
});
</script>
jQuery('#datetimepicker2').datetimepicker({
datepicker:false,
format:'H:i',
defaultTime:'00:00'
});

Categories