Skip to content

Commit

Permalink
Migrating dateTimeFormatService and format-timer.pipe (oppia#7827)
Browse files Browse the repository at this point in the history
* migrating dateTimeFormatService and format-timer.pipe

* migrating DateTimeSpec file

* fixed styling

* fixed order

* merging develop

* fixing transform

* changing timer to time

* moving filter

* fixing types
  • Loading branch information
Showtim3 authored and bansalnitish committed Nov 5, 2019
1 parent b15f3c1 commit 3ff7b2a
Show file tree
Hide file tree
Showing 4 changed files with 111 additions and 73 deletions.
32 changes: 32 additions & 0 deletions core/templates/dev/head/filters/format-timer.pipe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Copyright 2019 The Oppia Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

/**
* @fileoverview FormatTime filter for Oppia.
*/

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({name: 'formatTime'})
export class FormatTimePipe implements PipeTransform {
transform(input: number): string {
let formatNum = function(n) {
return (n < 10 ? '0' : '') + n;
};

let seconds = input % 60;
let minutes = Math.floor(input / 60);
return (formatNum(minutes) + ':' + formatNum(seconds));
}
}
5 changes: 4 additions & 1 deletion core/templates/dev/head/services/UpgradedServices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,11 @@ import { AlertsService } from 'services/alerts.service';
import { LoggerService } from 'services/contextual/logger.service';
import { BackgroundMaskService } from
'services/stateful/background-mask.service';
import { DateTimeFormatService } from 'services/date-time-format.service';
import { DeviceInfoService } from 'services/contextual/device-info.service';
import { DocumentAttributeCustomizationService } from
'services/contextual/document-attribute-customization.service';
import { FormatTimePipe } from 'filters/format-timer.pipe';
import { MetaTagCustomizationService } from
'services/contextual/meta-tag-customization.service';
import { SidebarStatusService } from 'domain/sidebar/sidebar-status.service';
Expand All @@ -42,9 +44,10 @@ export class UpgradedServices {
upgradedServices = {
'AlertsService': new AlertsService(new LoggerService()),
'BackgroundMaskService': new BackgroundMaskService(),
'DeviceInfoService': new DeviceInfoService(new WindowRef()),
'DateTimeFormatService': new DateTimeFormatService(new FormatTimePipe()),
'DocumentAttributeCustomizationService':
new DocumentAttributeCustomizationService(new WindowRef()),
'DeviceInfoService': new DeviceInfoService(new WindowRef()),
'MetaTagCustomizationService': new MetaTagCustomizationService(
new WindowRef()),
'SidebarStatusService': new SidebarStatusService(
Expand Down
64 changes: 25 additions & 39 deletions core/templates/dev/head/services/date-time-format.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,45 +16,31 @@
* @fileoverview Unit test for DateTimeFormatService.
*/

// TODO(#7222): Remove the following block of unnnecessary imports once
// the code corresponding to the spec is upgraded to Angular 8.
import { UpgradedServices } from 'services/UpgradedServices';
// ^^^ This block is to be removed.

require('services/date-time-format.service.ts');

describe('Datetime Formatter', function() {
beforeEach(angular.mock.module('oppia'));
beforeEach(angular.mock.module('oppia', function($provide) {
var ugs = new UpgradedServices();
for (let [key, value] of Object.entries(ugs.upgradedServices)) {
$provide.value(key, value);
}
}));

describe('datetimeformatter', function() {
// This corresponds to Fri, 21 Nov 2014 09:45:00 GMT.
var NOW_MILLIS = 1416563100000;
var df = null;
var OldDate = Date;

beforeEach(angular.mock.inject(function($injector) {
df = $injector.get('DateTimeFormatService');

// Mock Date() to give a time of NOW_MILLIS in GMT. (Unfortunately, there
// doesn't seem to be a good way to set the timezone locale directly.)
spyOn(window, 'Date').and.callFake(function() {
return new OldDate(NOW_MILLIS);
});
}));

it('should correctly indicate recency', function() {
// 1 second ago is recent.
expect(df.isRecent(NOW_MILLIS - 1)).toBe(true);
// 72 hours ago is recent.
expect(df.isRecent(NOW_MILLIS - 72 * 60 * 60 * 1000)).toBe(true);
// 8 days ago is not recent.
expect(df.isRecent(NOW_MILLIS - 8 * 24 * 60 * 60 * 1000)).toBe(false);
import { DateTimeFormatService } from 'services/date-time-format.service';
import { FormatTimePipe } from 'filters/format-timer.pipe';

describe('datetimeformatter', () => {
// This corresponds to Fri, 21 Nov 2014 09:45:00 GMT.
let NOW_MILLIS = 1416563100000;
let df: DateTimeFormatService;
let OldDate = Date;

beforeEach(() => {
df = new DateTimeFormatService(new FormatTimePipe());

// Mock Date() to give a time of NOW_MILLIS in GMT. (Unfortunately, there
// doesn't seem to be a good way to set the timezone locale directly.)
spyOn(window, 'Date').and.callFake(function() {
return new OldDate(NOW_MILLIS);
});
});

it('should correctly indicate recency', () => {
// 1 second ago is recent.
expect(df.isRecent(NOW_MILLIS - 1)).toBe(true);
// 72 hours ago is recent.
expect(df.isRecent(NOW_MILLIS - 72 * 60 * 60 * 1000)).toBe(true);
// 8 days ago is not recent.
expect(df.isRecent(NOW_MILLIS - 8 * 24 * 60 * 60 * 1000)).toBe(false);
});
});
83 changes: 50 additions & 33 deletions core/templates/dev/head/services/date-time-format.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,36 +17,53 @@
* since the Epoch to human-readable dates.
*/

angular.module('oppia').factory('DateTimeFormatService', [
'$filter', function($filter) {
return {
// Returns just the time if the local datetime representation has the
// same date as the current date. Otherwise, returns just the date if the
// local datetime representation has the same year as the current date.
// Otherwise, returns the full date (with the year abbreviated).
getLocaleAbbreviatedDatetimeString: function(millisSinceEpoch) {
var date = new Date(millisSinceEpoch);
if (date.toLocaleDateString() === new Date().toLocaleDateString()) {
return date.toLocaleTimeString([], {
hour: 'numeric',
minute: 'numeric',
hour12: true
});
} else if (date.getFullYear() === new Date().getFullYear()) {
return $filter('date')(date, 'MMM d');
} else {
return $filter('date')(date, 'shortDate');
}
},
// Returns just the date.
getLocaleDateString: function(millisSinceEpoch) {
var date = new Date(millisSinceEpoch);
return date.toLocaleDateString();
},
// Returns whether the date is at most one week before the current date.
isRecent: function(millisSinceEpoch) {
var ONE_WEEK_IN_MILLIS = 7 * 24 * 60 * 60 * 1000;
return new Date().getTime() - millisSinceEpoch < ONE_WEEK_IN_MILLIS;
}
};
}]);
import { downgradeInjectable } from '@angular/upgrade/static';
import { Injectable } from '@angular/core';
import moment from 'moment';

import { FormatTimePipe } from 'filters/format-timer.pipe';


@Injectable({
providedIn: 'root'
})
export class DateTimeFormatService {
constructor(private formatTimePipe: FormatTimePipe) {}

// Returns just the time if the local datetime representation has the
// same date as the current date. Otherwise, returns just the date if the
// local datetime representation has the same year as the current date.
// Otherwise, returns the full date (with the year abbreviated).
getLocaleAbbreviatedDatetimeString(millisSinceEpoch: number): string {
let date = new Date(millisSinceEpoch);
if (date.toLocaleDateString() === new Date().toLocaleDateString()) {
return date.toLocaleTimeString([], {
hour: 'numeric',
minute: 'numeric',
hour12: true
});
} else if (date.getFullYear() === new Date().getFullYear()) {
let transformedDate = this.formatTimePipe.transform(Number(date));
// moment will return Oct 10
return moment(transformedDate).format('MMM d');
} else {
let transformedDate = this.formatTimePipe.transform(Number(date));
// moment will return 10/22/35(shortDate)
return moment(transformedDate).format('MM/DD/YY');
}
}

// Returns just the date.
getLocaleDateString(millisSinceEpoch: number): string {
let date = new Date(millisSinceEpoch);
return date.toLocaleDateString();
}
// Returns whether the date is at most one week before the current date.
isRecent(millisSinceEpoch: number): boolean {
let ONE_WEEK_IN_MILLIS = 7 * 24 * 60 * 60 * 1000;
return new Date().getTime() - millisSinceEpoch < ONE_WEEK_IN_MILLIS;
}
}

angular.module('oppia').factory(
'DateTimeFormatService', downgradeInjectable(DateTimeFormatService));

0 comments on commit 3ff7b2a

Please sign in to comment.