-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtime-service.ts
74 lines (51 loc) · 2.62 KB
/
time-service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import { Persistence } from "https://deno.land/x/[email protected]/persistence.ts"
export class TimeService {
public static async getAllTimeZoneEntries(): Promise<any[]> {
const pathToTimeZonesFile = 'https://raw.githubusercontent.com/michael-spengler/time/master/timezones.json'
const allTimeZoneEntries = JSON.parse(await Persistence.readFromRemoteFile(pathToTimeZonesFile))
return allTimeZoneEntries
}
public static getTimeByOffset(offset: string) {
const minutes = Number(TimeService.convertOffsetToMinutes(offset))
let getDifferenceToUtcInMilisec = minutes * 60000;
let getUTCMilisecond = new Date().getTime();
const result = new Date(getUTCMilisecond - getDifferenceToUtcInMilisec).toISOString()
return result.substr(11, 8)
}
public static async getTimeZone(countryCode: string, cityName: string): Promise<string> {
const entry = await TimeService.getTimeZoneEntry(countryCode, cityName)
return entry.timezone
}
public static async getTimeZoneOffset(countryCode: string, cityName: string, convertToMinutes: boolean = false): Promise<string> {
const entry = await TimeService.getTimeZoneEntry(countryCode, cityName)
if (convertToMinutes) {
return TimeService.convertOffsetToMinutes(entry.offset).toString()
}
return entry.offset
}
public static async getTimeZoneOffsetDST(countryCode: string, cityName: string, convertToMinutes: boolean = false): Promise<string> {
const entry = await TimeService.getTimeZoneEntry(countryCode, cityName)
if (convertToMinutes) {
return TimeService.convertOffsetToMinutes(entry.dayLightSavingTimeOffset).toString()
}
return entry.dayLightSavingTimeOffset
}
public static convertOffsetToMinutes(offsetString: string): number {
const preFix = offsetString.substr(0, 1)
const hours = Number(offsetString.substr(1, 2))
const minutes = Number(offsetString.substr(4, 2))
const complete = (hours * 60) + (minutes)
if (preFix === '+') {
return complete * -1
}
return complete
}
private static async getTimeZoneEntry(countryCode: string, cityName: string): Promise<any> {
const allTimeZones = await TimeService.getAllTimeZoneEntries()
const entry = allTimeZones.filter((e: any) => e.iso2 === countryCode && (e.city === cityName || e.city_ascii === cityName))[0]
if (entry === undefined) {
throw new Error(`I could not find the timezone for ${cityName} (${countryCode})`)
}
return entry
}
}