How to configure #nuxtjs/moment to use relativeTime settings for en locale - momentjs

I am trying to display relative time in moment using the moment(...).fromNow()
I am using the #nuxtjs/moment module
It currently displays relative time as "15 days ago" etc. I want to change that to "15 d"
As per THIS answer is how it can be done currently
moment.updateLocale('en', {
relativeTime : {
future: "in %s",
past: "%s ago",
s: function (number, withoutSuffix, key, isFuture){
return '00:' + (number<10 ? '0':'') + number + ' minutes';
},
m: "01:00 minutes",
mm: function (number, withoutSuffix, key, isFuture){
return (number<10 ? '0':'') + number + ':00' + ' 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"
}
});
How do I apply this to the #nuxtjs/moment module

Make a nuxt plugin and access the $moment using context
export default (context) => {
context.$moment.updateLocale('en', {
relativeTime: {
future: '%s',
past: '%s',
s: '1 s',
ss: '%d seconds',
m: '1 m',
mm: '%d m',
h: '1 h',
hh: '%d h',
d: '1 d',
dd: '%d d',
M: '1 M',
MM: '%d M',
y: '1 Y',
yy: '%d Y',
},
})
}

Related

FlatPickr: DateTime – Increase second datetime minDate (or minTime) by hours or minutes rather than full days

With great shame, I've now spent several hours across multiple days only to continue failing to figure this one out:
How can I create a flatpickr onChange event where the minDate (or minTime?) of the second datetime input is +x hours or minutes relative to the first datetime input selection? I can't figure out how to set a relative increase less than one full day.
These config options are successfully forcing the second input's minDate to be that of the first input's datetime output down to the minute, but will accept the very same time:
// Start Date and Time: input_144_5
const startDate = $('#input_144_5').flatpickr({
enableTime: true,
dateFormat: "Y-m-d H:i",
altInput: true,
altFormat: "D, F j \\a\\t h:i K",
defaultDate: new Date(),
onChange: function(selectedDates, dateStr, instance) {
endDate.set('minDate', new Date(dateStr))
}
});
// End Date and Time: input_144_6
const endDate = $('#input_144_6').flatpickr({
enableTime: true,
dateFormat: "Y-m-d H:i",
altInput: true,
altFormat: "D, F j \\a\\t h:i K",
});
While this one is successfully setting the second input's minimum to +1 full day:
// Start Date and Time: input_144_5
var startDate = $('#input_144_5').flatpickr({
enableTime: true,
dateFormat: "Y-m-d H:i",
altInput: true,
altFormat: "D, F j \\a\\t h:i K",
defaultDate: new Date(),
onChange: function(selectedDates, dateStr, instance) {
endDate.set('minDate', new Date(dateStr).fp_incr(1))
}
});
// End Date and Time: input_144_6
var endDate = $('#input_144_6').flatpickr({
enableTime: true,
dateFormat: "Y-m-d H:i",
altInput: true,
altFormat: "D, F j \\a\\t h:i K",
});
Is there any way to set—or restrict—fp_incr() in a way that only increases the minute value by +1, or maybe targets the minutes portion of the dateStr exclusively?
FlatPickr documentation here if helpful.

How to save flutter TimeOfDay to firebase?

I am working on a flutter application where I am showing a TimeRangepicker using this plugin: time_range_picker and I am getting TimeOfDay(09:00) + TimeOfDay(12:00) as a result by using this code:
onPressed: () async {
TimeRange result = await showTimeRangePicker(
use24HourFormat: false,
interval: Duration(minutes: 30),
context: context,
start: TimeOfDay(hour: 9, minute: 0),
end: TimeOfDay(hour: 12, minute: 0),
disabledTime: TimeRange(
startTime: TimeOfDay(hour: 23, minute: 0),
endTime: TimeOfDay(hour: 5, minute: 0)),
disabledColor: Colors.red.withOpacity(0.5),
strokeWidth: 4,
ticks: 24,
ticksOffset: -7,
ticksLength: 15,
ticksColor: Colors.grey,
labels: [
"12 pm",
"3 am",
"6 am",
"9 am",
"12 am",
"3 pm",
"6 pm",
"9 pm"
].asMap().entries.map((e) {
return ClockLabel.fromIndex(
idx: e.key, length: 8, text: e.value);
}).toList(),
labelOffset: 35,
rotateLabels: false,
padding: 60);
print("${result.startTime} + ${result.endTime}");
},
But the only problem is I can find an appropriate way to save this to firebase, I don't need date all I need is TimeOfDay.
There is no specific data type in Firestore for storing a time of day, so you'll have to map it to one of the existing types.
Some common mapping are:
Store the time of day as a string value, such as "07:55:00.000" (if you care up to millisecond precision)
Store the time of day as an offset from midnight, such as 28500 (as the number of seconds from midnight until 7:55 AM)
Store the time of day as a the time part of a fixed day in a Timestamp field. This is essentially a variant of the previous approach, with the offset being from the start of the epoch. Say that you pick the start of the epoch (January 1, 1970) as the fixed day, then the Timestamp's value would be 28500000 (in milliseconds).
All of these have valid use-case, so pick whichever one works best for the use-cases of your app.
In the common use case whereby only the hour and minute are required a simple map of these values will suffice.
Map timeOfDayToFirebase(TimeOfDay timeOfDay){
return {
'hour':timeOfDay.hour,
'minute':timeOfDay.minute
}
}
TimeOfDay firebaseToTimeOfDay(Map data){
return TimeOfDay(
hour: data['hour'],
minute: data['minute']);
}
var myTimeOfDayObject=TimeOfDay.now();
firebase.update({'time': timeOfDayToFirebase(myTimeOfDayObject)});
This way you don't have to worry about managing offsets, unintended locale changes and so forth.
You can use something like this
class ClassModel {
TimeOfDay time;
ClassModel({
required this.time,
});
Map<String, dynamic> toMap() {
return <String, dynamic>{
'time': (time.hour.toString() + "*" + time.minute.toString()),
};
}
factory ClassModel.fromMap(Map<String, dynamic> map) {
return ClassModel(
time: TimeOfDay(
hour: int.parse(map['time'].toString().split("*").first),
minute: int.parse(map['time'].toString().split("*").last)),
);
}
}

How to set locale locally for moment.js

The below code gives invalid date
moment.locale('en');
var localLocale = moment('enero 22, 2017', 'MMMM DD, YYYY');
localLocale.locale('es');
alert(localLocale.format('L'));'
You will need to import that particular locale js from Moment.js repo.
I've imported this in below code and this code works perfectly:
https://raw.githubusercontent.com/moment/moment/develop/locale/es.js
//! moment.js locale configuration
//! locale : Spanish [es]
//! author : Julio Napurí : https://github.com/julionc
;(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined'
&& typeof require === 'function' ? factory(require('../moment')) :
typeof define === 'function' && define.amd ? define(['../moment'], factory) :
factory(global.moment)
}(this, (function (moment) { 'use strict';
var monthsShortDot = 'ene._feb._mar._abr._may._jun._jul._ago._sep._oct._nov._dic.'.split('_');
var monthsShort = 'ene_feb_mar_abr_may_jun_jul_ago_sep_oct_nov_dic'.split('_');
var monthsParse = [/^ene/i, /^feb/i, /^mar/i, /^abr/i, /^may/i, /^jun/i, /^jul/i, /^ago/i, /^sep/i, /^oct/i, /^nov/i, /^dic/i];
var monthsRegex = /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre|ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i;
var es = moment.defineLocale('es', {
months : 'enero_febrero_marzo_abril_mayo_junio_julio_agosto_septiembre_octubre_noviembre_diciembre'.split('_'),
monthsShort : function (m, format) {
if (!m) {
return monthsShortDot;
} else if (/-MMM-/.test(format)) {
return monthsShort[m.month()];
} else {
return monthsShortDot[m.month()];
}
},
monthsRegex : monthsRegex,
monthsShortRegex : monthsRegex,
monthsStrictRegex : /^(enero|febrero|marzo|abril|mayo|junio|julio|agosto|septiembre|octubre|noviembre|diciembre)/i,
monthsShortStrictRegex : /^(ene\.?|feb\.?|mar\.?|abr\.?|may\.?|jun\.?|jul\.?|ago\.?|sep\.?|oct\.?|nov\.?|dic\.?)/i,
monthsParse : monthsParse,
longMonthsParse : monthsParse,
shortMonthsParse : monthsParse,
weekdays : 'domingo_lunes_martes_miércoles_jueves_viernes_sábado'.split('_'),
weekdaysShort : 'dom._lun._mar._mié._jue._vie._sáb.'.split('_'),
weekdaysMin : 'do_lu_ma_mi_ju_vi_sá'.split('_'),
weekdaysParseExact : true,
longDateFormat : {
LT : 'H:mm',
LTS : 'H:mm:ss',
L : 'DD/MM/YYYY',
LL : 'D [de] MMMM [de] YYYY',
LLL : 'D [de] MMMM [de] YYYY H:mm',
LLLL : 'dddd, D [de] MMMM [de] YYYY H:mm'
},
calendar : {
sameDay : function () {
return '[hoy a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
nextDay : function () {
return '[mañana a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
nextWeek : function () {
return 'dddd [a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
lastDay : function () {
return '[ayer a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
lastWeek : function () {
return '[el] dddd [pasado a la' + ((this.hours() !== 1) ? 's' : '') + '] LT';
},
sameElse : 'L'
},
relativeTime : {
future : 'en %s',
past : 'hace %s',
s : 'unos segundos',
m : 'un minuto',
mm : '%d minutos',
h : 'una hora',
hh : '%d horas',
d : 'un día',
dd : '%d días',
M : 'un mes',
MM : '%d meses',
y : 'un año',
yy : '%d años'
},
dayOfMonthOrdinalParse : /\d{1,2}º/,
ordinal : '%dº',
week : {
dow : 1, // Monday is the first day of the week.
doy : 4 // The week that contains Jan 4th is the first week of the year.
}
});
return es;
})));
Your Code:
moment.updateLocale('es');
var localLocale = moment('enero 22, 2017', 'MMMM DD, YYYY');
alert(localLocale.format('L'));
Demo:
http://jsfiddle.net/6df2xf80/

using a php unix timestamp with moment.js

Can't seem to get unix timestamps working with moment.js...
date_create is equal to my php unix timestamp in this case and I want to use that as the startDate, minDate, and a few other places... I am not getting an error, but it is displaying as 'December 31, 1969 # 7:00 pm' which is obviously not correct.
What am I doing wrong here? The goal is to have the correct date/time shown as computers time from the utc timestamp given.
For instance 1401079499 is 05 / 26 / 14 # 4:44:59am UTC, but this would show as May 26, ‎2014‎ ‎12‎:‎44‎:‎59‎ am ‎on my own computer being gmt-4
var date_create = $('#dashboard-report-range #date-display').html(); //equals 1401079499
//date range stuff
$('#dashboard-report-range').daterangepicker({
opens: 'left',
startDate: moment.unix(date_create).startOf('day'),
endDate: moment().endOf('day'),
minDate: moment.unix(date_create).startOf('day'),
maxDate: moment().endOf('day'),
showDropdowns: false,
showWeekNumbers: true,
timePicker: true,
timePickerIncrement: 1,
timePicker12Hour: true,
ranges: {
'All': [moment.unix(date_create).startOf('day'), moment().endOf('day')],
'Today': [moment().startOf('day'), moment().endOf('day')],
'Yesterday': [moment().subtract('days', 1).startOf('day'), moment().subtract('days', 1).endOf('day')],
'Last 7 Days': [moment().subtract('days', 6).startOf('day'), moment().endOf('day')],
'Last 30 Days': [moment().subtract('days', 29).startOf('day'), moment().endOf('day')],
'This Month': [moment().startOf('month'), moment().endOf('month')],
'Last Month': [moment().subtract('month', 1).startOf('month'), moment().subtract('month', 1).endOf('month')]
},
buttonClasses: ['btn'],
applyClass: 'btn-sm btn-success',
cancelClass: 'btn-sm btn-default',
format: 'MM/DD/YYYY',
//format: 'MM-DD-YY',
separator: ' to ',
locale: {
applyLabel: 'Apply',
fromLabel: 'From',
toLabel: 'To',
customRangeLabel: 'Custom Range',
daysOfWeek: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
firstDay: 1
}
},
function (start, end) {
$('#dashboard-report-range #date-display').html('<span class="ddate_start">' + start.format('MMMM D, YYYY [#] h:mm a') + '</span> <i class="fa fa-arrows-h"></i> <span class="ddate_end">' + end.format('MMMM D, YYYY [#] h:mm a') + '</span>');
$('#dashboard-report-range #date-start').html( start.unix() );
$('#dashboard-report-range #date-end').html( end.unix() );
dt.draw();
}
);
$('#dashboard-report-range #date-display').html('<span class="ddate_start">' + moment.unix(date_create).startOf('day').format('MMMM D, YYYY [#] h:mm a') + '</span> <i class="fa fa-arrows-h"></i> <span class="ddate_end">' + moment().endOf('day').format('MMMM D, YYYY [#] h:mm a') + '</span>');
$('#dashboard-report-range').show();
};
EDIT - solution :
I had forgotten to change the id I grab the unix timestamp from... $('#dashboard-report-range #date-create').html(); With that change everything works as it should.
Multiply the timestamp by 1000.
PHP returns timestamp in seconds, but JS understands it as milliseconds.

agendaDay row time format in fullCalendar

I am trying to set the time format in my calendar rows to appear as 1pm - 2pm, 2pm - 3pm, 3pm- 4pm, etc.
I have tried the following:
agenda: 'h:mm{ - h:mm}',
axisFormat: 'h:mm{ - h:mm}',
day: 'h:mm{ - h:mm}',
axisFormat: 'h(:mm)tt',
timeFormat: {
agenda: 'h:mm{ - h:mm}'
},
but none of the above, either alone or in combination seem to work for me.
I initialize my calendar as below:
$('#calendar').fullCalendar({
defaultView: 'agendaDay',
allDaySlot: false,
firstHour: 9,
minTime: 9,
maxTime: 19,
selectable: true,
unselectAuto: true,
slotMinutes: 60,
weekends: false,
year: current_year,
month: current_month,
date: current_day,
columnFormat: '',
FullCalendar does not provide a "to" time for the axisFormat and therefore the { - h:mm} part of you axisFormat is ignored.
And I don't think there's any way to do it without editing the FullCalendar source code.
But if you are feeling adventurous you could do the following changes in fullcalendar.js around line 3207:
d = zeroDate();
maxd = addMinutes(cloneDate(d), maxMinute);
addMinutes(d, minMinute);
// Add two lines
var toD = cloneDate(d);
addMinutes(toD, opt('slotMinutes'));
slotCnt = 0;
for (i=0; d < maxd; i++) {
minutes = d.getMinutes();
s +=
"<tr class='fc-slot" + i + ' ' + (!minutes ? '' : 'fc-minor') + "'>" +
"<th class='fc-agenda-axis " + headerClass + "'>" +
// Changed line from "formatDate(d, opt('axisFormat')...)" to "formatDates(d, toD, opt('axisFormat')...)"
((!slotNormal || !minutes) ? formatDates(d, toD, opt('axisFormat')) : ' ') +
"</th>" +
"<td class='" + contentClass + "'>" +
"<div style='position:relative'> </div>" +
"</td>" +
"</tr>";
addMinutes(d, opt('slotMinutes'));
// Add line
addMinutes(toD, opt('slotMinutes'));
slotCnt++;
}

Resources