MOBILE-4116 core: Avoid using Date instances if possible

When the date can be affected by time zone, always use moment
main
Dani Palou 2022-07-27 10:13:21 +02:00
parent 88a19ea066
commit 844c14b8cb
13 changed files with 35 additions and 33 deletions

View File

@ -509,7 +509,7 @@ class AddonCalendarMonthSlidesItemsManagerSource extends CoreSwipeSlidesDynamicI
const weekDays = AddonCalendar.getWeekDays(result.daynames[0].dayno);
const weeks = result.weeks as AddonCalendarWeek[];
const currentDay = new Date().getDate();
const currentDay = moment().date();
const currentTime = CoreTimeUtils.timestamp();
const preloadedMonth: PreloadedMonth = {

View File

@ -136,8 +136,8 @@ export class AddonCalendarHelperProvider {
const result = {};
events.forEach((event) => {
const treatedDay = moment(new Date(event.timestart * 1000));
const endDay = moment(new Date((event.timestart + event.timeduration) * 1000));
const treatedDay = moment(event.timestart * 1000);
const endDay = moment((event.timestart + event.timeduration) * 1000);
// Add the event to all the days it lasts.
while (!treatedDay.isAfter(endDay, 'day')) {
@ -661,7 +661,7 @@ export class AddonCalendarHelperProvider {
// Fetch months and days.
fetchTimestarts.map((fetchTime) => {
const day = moment(new Date(fetchTime * 1000));
const day = moment(fetchTime * 1000);
const monthId = this.getMonthId(day);
if (!treatedMonths[monthId]) {
@ -697,7 +697,7 @@ export class AddonCalendarHelperProvider {
// Invalidate months and days.
invalidateTimestarts.map((fetchTime) => {
const day = moment(new Date(fetchTime * 1000));
const day = moment(fetchTime * 1000);
const monthId = this.getMonthId(day);
if (!treatedMonths[monthId]) {

View File

@ -20,6 +20,7 @@ import { CoreContentLinksAction } from '@features/contentlinks/services/contentl
import { CoreNavigator } from '@services/navigator';
import { makeSingleton } from '@singletons';
import { AddonCalendar } from '../calendar';
import moment from 'moment-timezone';
const SUPPORTED_VIEWS = ['month', 'mini', 'minithree', 'day', 'upcoming', 'upcoming_mini'];
@ -54,9 +55,9 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler
};
const timestamp = params.time ? Number(params.time) * 1000 : Date.now();
const date = new Date(timestamp);
stateParams.year = date.getFullYear();
stateParams.month = date.getMonth() + 1;
const momentInstance = moment(timestamp);
stateParams.year = momentInstance.year();
stateParams.month = momentInstance.month() + 1;
CoreNavigator.navigateToSitePath('/calendar/index', {
params: stateParams,
@ -71,10 +72,10 @@ export class AddonCalendarViewLinkHandlerService extends CoreContentLinksHandler
};
const timestamp = params.time ? Number(params.time) * 1000 : Date.now();
const date = new Date(timestamp);
stateParams.year = date.getFullYear();
stateParams.month = date.getMonth() + 1;
stateParams.day = date.getDate();
const momentInstance = moment(timestamp);
stateParams.year = momentInstance.year();
stateParams.month = momentInstance.month() + 1;
stateParams.day = momentInstance.date();
CoreNavigator.navigateToSitePath('/calendar/day', { params: stateParams, siteId });

View File

@ -1125,7 +1125,7 @@ export class AddonMessagesDiscussionPage implements OnInit, OnDestroy, AfterView
useridfrom: this.currentUserId,
smallmessage: text,
text: text,
timecreated: new Date().getTime(),
timecreated: Date.now(),
};
message.showDate = this.showDate(message, this.messages[this.messages.length - 1]);
this.addMessage(message, false);

View File

@ -313,7 +313,7 @@ export class AddonMessagesOfflineProvider {
touserid: toUserId,
useridfrom: site.getUserId(),
smallmessage: message,
timecreated: new Date().getTime(),
timecreated: Date.now(),
deviceoffline: CoreNetwork.isOnline() ? 0 : 1,
};

View File

@ -15,6 +15,7 @@
import { Component } from '@angular/core';
import { CoreTimeUtils } from '@services/utils/time';
import { Translate } from '@singletons';
import moment, { Moment } from 'moment-timezone';
import { AddonModDataFieldPluginBaseComponent } from '../../../classes/base-field-plugin-component';
/**
@ -43,7 +44,7 @@ export class AddonModDataFieldDateComponent extends AddonModDataFieldPluginBaseC
return;
}
let date: Date;
let momentInstance: Moment;
// Calculate format to use.
this.format = CoreTimeUtils.fixFormatForDatetime(CoreTimeUtils.convertPHPToMoment(
@ -55,27 +56,25 @@ export class AddonModDataFieldDateComponent extends AddonModDataFieldPluginBaseC
if (this.searchMode) {
this.addControl('f_' + this.field.id + '_z');
date = this.searchFields!['f_' + this.field.id + '_y']
? new Date(this.searchFields!['f_' + this.field.id + '_y'] + '-' +
momentInstance = this.searchFields!['f_' + this.field.id + '_y']
? moment(this.searchFields!['f_' + this.field.id + '_y'] + '-' +
this.searchFields!['f_' + this.field.id + '_m'] + '-' + this.searchFields!['f_' + this.field.id + '_d'])
: new Date();
: moment();
this.searchFields!['f_' + this.field.id] = CoreTimeUtils.toDatetimeFormat(date.getTime());
this.searchFields!['f_' + this.field.id] = CoreTimeUtils.toDatetimeFormat(momentInstance.unix() * 1000);
} else {
date = this.value?.content
? new Date(parseInt(this.value.content, 10) * 1000)
: new Date();
momentInstance = this.value?.content
? moment(parseInt(this.value.content, 10) * 1000)
: moment();
}
const seconds = Math.floor(date.getTime() / 1000);
this.addControl('f_' + this.field.id, CoreTimeUtils.toDatetimeFormat(seconds * 1000));
this.addControl('f_' + this.field.id, CoreTimeUtils.toDatetimeFormat(momentInstance.unix() * 1000));
if (!this.searchMode && !this.value?.content) {
this.onFieldInit.emit({
fieldid: this.field.id,
content: String(seconds),
content: String(momentInstance.unix()),
});
}
}

View File

@ -270,7 +270,7 @@ export class AddonModDataEditPage implements OnInit {
const modal = await CoreDomUtils.showModalLoading('core.sending', true);
// Create an ID to assign files.
const entryTemp = this.entryId ? this.entryId : - (new Date().getTime());
const entryTemp = this.entryId ? this.entryId : - (Date.now());
let editData: AddonModDataEntryWSField[] = [];
try {

View File

@ -262,7 +262,7 @@ export class AddonModDataOfflineProvider {
): Promise<AddonModDataEntryDBRecord> {
const site = await CoreSites.getSite(siteId);
timemodified = timemodified || new Date().getTime();
timemodified = timemodified || Date.now();
entryId = entryId === undefined || entryId === null ? -timemodified : entryId;
const entry: AddonModDataEntryDBRecord = {

View File

@ -170,7 +170,7 @@ export class AddonModForumOfflineProvider {
options: JSON.stringify(options || {}),
groupid: groupId || AddonModForumProvider.ALL_PARTICIPANTS,
userid: userId || site.getUserId(),
timecreated: timeCreated || new Date().getTime(),
timecreated: timeCreated || Date.now(),
};
await site.getDb().insertRecord(DISCUSSIONS_TABLE, data);
@ -325,7 +325,7 @@ export class AddonModForumOfflineProvider {
message: message,
options: JSON.stringify(options || {}),
userid: userId || site.getUserId(),
timecreated: new Date().getTime(),
timecreated: Date.now(),
};
await site.getDb().insertRecord(REPLIES_TABLE, data);

View File

@ -137,7 +137,7 @@ export class AddonModSurveyOfflineProvider {
courseid: courseId,
userid: userId,
answers: JSON.stringify(answers),
timecreated: new Date().getTime(),
timecreated: Date.now(),
};
await site.getDb().insertRecord(SURVEY_TABLE, entry);

View File

@ -114,7 +114,7 @@ export class CoreUserAvatarComponent implements OnInit, OnChanges, OnDestroy {
if (this.user.lastaccess) {
// If the time has passed, don't show the online status.
const time = new Date().getTime() - this.timetoshowusers;
const time = Date.now() - this.timetoshowusers;
return this.user.lastaccess * 1000 >= time;
} else {

View File

@ -82,6 +82,7 @@ import { CoreComponentsRegistry } from '@singletons/components-registry';
import { CoreDom } from '@singletons/dom';
import { CoreForms } from '@singletons/form';
import { CoreText } from '@singletons/text';
import { CoreTime } from '@singletons/time';
import { CoreUrl } from '@singletons/url';
import { CoreWindow } from '@singletons/window';
import { CoreCache } from '@classes/cache';
@ -354,6 +355,7 @@ export class CoreCompileProvider {
instance['CoreDom'] = CoreDom;
instance['CoreForms'] = CoreForms;
instance['CoreText'] = CoreText;
instance['CoreTime'] = CoreTime;
instance['CoreUrl'] = CoreUrl;
instance['CoreWindow'] = CoreWindow;
instance['CoreCache'] = CoreCache;

View File

@ -1418,7 +1418,7 @@ export class CoreCourseProvider {
id: courseId,
status: status,
previous: previousStatus,
updated: new Date().getTime(),
updated: Date.now(),
downloadTime: downloadTime,
previousDownloadTime: previousDownloadTime,
});