Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function formatTime(time: number, format: string): string {
- // create 400 element array with year lengths
- var yearLengthArray : number[] = [...Array(400).keys()].map(i =>
- i % 4 ?
- 365 :
- i % 100 ?
- 366 :
- i % 400 ?
- 365 :
- 366
- ),
- yearTimeStamp : number = time,
- year : number = 1970,
- yearLengthIndex : number = 370,
- month : number = 0,
- monthTimeStamp : number
- while (yearTimeStamp >= 0) // loop through years and subtract the correct time
- monthTimeStamp = yearTimeStamp, // reusing monthTimeStamp here because it works somehow
- yearTimeStamp -= yearLengthArray[yearLengthIndex] * 86400,
- year++,
- yearLengthIndex=(yearLengthIndex + 1) % 400
- while (monthTimeStamp >= 0) // loop through months and subtract the correct time
- yearTimeStamp = monthTimeStamp, // yearTimeStamp is now unused so we can reuse it here
- monthTimeStamp -= [
- [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
- [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
- ]
- [yearLengthArray[yearLengthIndex] - 365] // get "if leap year" by subtracting 365 from length
- [month] * 86400,
- month++
- format = format.replace('\\', '\\\\') // escape any \'s from the format
- Object.entries({ // compute values for each format option as well as hold regexp's for selecting any unescaped format option
- d: [
- `0${Math.floor(1 + yearTimeStamp / 86400)}`.slice(-2),
- /((?:[^\\]|^)(?:\\\\)*(?!\\))d/g
- ],
- A: [
- [
- "Thurs", "Fri", "Satur", "Sun", "Mon", "Tues", "Wednes"
- ][Math.floor(time / 86400) % 7] + "day",
- /((?:[^\\]|^)(?:\\\\)*(?!\\))A/g
- ],
- B: [
- [
- "January", "February", "March", "April", "May", "June",
- "July", "August", "September", "October", "November", "December"
- ][month - 1],
- /((?:[^\\]|^)(?:\\\\)*(?!\\))B/g
- ],
- Y: [
- (year - 1).toString(),
- /((?:[^\\]|^)(?:\\\\)*(?!\\))Y/g
- ],
- H: [
- `0${Math.floor(time / 3600) % 24}`.slice(-2),
- /((?:[^\\]|^)(?:\\\\)*(?!\\))H/g
- ],
- h: [
- `0${Math.floor(time / 3600) % 12}`.slice(-2),
- /((?:[^\\]|^)(?:\\\\)*(?!\\))h/g
- ],
- M: [
- `0${Math.floor(time / 60) % 60}`.slice(-2),
- /((?:[^\\]|^)(?:\\\\)*(?!\\))M/g
- ],
- S: [
- `0${time % 60}`.slice(-2),
- /((?:[^\\]|^)(?:\\\\)*(?!\\))S/g
- ],
- p: [
- (Math.floor(time / 43200) % 2)?"pm":"am",
- /((?:[^\\]|^)(?:\\\\)*(?!\\))p/g
- ]
- }).forEach((i)=>
- format = format.replace(
- i[1][1], // selection regexp
- // escape every character of result as to prevent "T10ursday" (where the result of a previous replacement is treated as a format option)
- `$1\\${[...i[1][0] as string].join('\\')}`
- )
- )
- return format.replace(/\\(.)/g, '$1') // unescape the result
- }
Advertisement
Add Comment
Please, Sign In to add comment