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 weekDays = AddonCalendar.getWeekDays(result.daynames[0].dayno);
const weeks = result.weeks as AddonCalendarWeek[]; const weeks = result.weeks as AddonCalendarWeek[];
const currentDay = new Date().getDate(); const currentDay = moment().date();
const currentTime = CoreTimeUtils.timestamp(); const currentTime = CoreTimeUtils.timestamp();
const preloadedMonth: PreloadedMonth = { const preloadedMonth: PreloadedMonth = {

View File

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

View File

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

View File

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

View File

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

View File

@ -15,6 +15,7 @@
import { Component } from '@angular/core'; import { Component } from '@angular/core';
import { CoreTimeUtils } from '@services/utils/time'; import { CoreTimeUtils } from '@services/utils/time';
import { Translate } from '@singletons'; import { Translate } from '@singletons';
import moment, { Moment } from 'moment-timezone';
import { AddonModDataFieldPluginBaseComponent } from '../../../classes/base-field-plugin-component'; import { AddonModDataFieldPluginBaseComponent } from '../../../classes/base-field-plugin-component';
/** /**
@ -43,7 +44,7 @@ export class AddonModDataFieldDateComponent extends AddonModDataFieldPluginBaseC
return; return;
} }
let date: Date; let momentInstance: Moment;
// Calculate format to use. // Calculate format to use.
this.format = CoreTimeUtils.fixFormatForDatetime(CoreTimeUtils.convertPHPToMoment( this.format = CoreTimeUtils.fixFormatForDatetime(CoreTimeUtils.convertPHPToMoment(
@ -55,27 +56,25 @@ export class AddonModDataFieldDateComponent extends AddonModDataFieldPluginBaseC
if (this.searchMode) { if (this.searchMode) {
this.addControl('f_' + this.field.id + '_z'); this.addControl('f_' + this.field.id + '_z');
date = this.searchFields!['f_' + this.field.id + '_y'] momentInstance = this.searchFields!['f_' + this.field.id + '_y']
? new Date(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']) 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 { } else {
date = this.value?.content momentInstance = this.value?.content
? new Date(parseInt(this.value.content, 10) * 1000) ? moment(parseInt(this.value.content, 10) * 1000)
: new Date(); : moment();
} }
const seconds = Math.floor(date.getTime() / 1000); this.addControl('f_' + this.field.id, CoreTimeUtils.toDatetimeFormat(momentInstance.unix() * 1000));
this.addControl('f_' + this.field.id, CoreTimeUtils.toDatetimeFormat(seconds * 1000));
if (!this.searchMode && !this.value?.content) { if (!this.searchMode && !this.value?.content) {
this.onFieldInit.emit({ this.onFieldInit.emit({
fieldid: this.field.id, 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); const modal = await CoreDomUtils.showModalLoading('core.sending', true);
// Create an ID to assign files. // 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[] = []; let editData: AddonModDataEntryWSField[] = [];
try { try {

View File

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

View File

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

View File

@ -137,7 +137,7 @@ export class AddonModSurveyOfflineProvider {
courseid: courseId, courseid: courseId,
userid: userId, userid: userId,
answers: JSON.stringify(answers), answers: JSON.stringify(answers),
timecreated: new Date().getTime(), timecreated: Date.now(),
}; };
await site.getDb().insertRecord(SURVEY_TABLE, entry); 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 (this.user.lastaccess) {
// If the time has passed, don't show the online status. // 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; return this.user.lastaccess * 1000 >= time;
} else { } else {

View File

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

View File

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