File tree Expand file tree Collapse file tree 2 files changed +114
-64
lines changed
Expand file tree Collapse file tree 2 files changed +114
-64
lines changed Original file line number Diff line number Diff line change 3232 }
3333 }
3434 }
35+ function changeFormat ( ) {
36+ const elems = document . getElementsByClassName ( "time" ) ;
37+ for ( let i = 0 ; i < elems . length ; i ++ ) {
38+ const elem = elems [ i ] ;
39+ const timeText = elem . innerHTML ;
40+ const [ newTime , curFormat ] = getNewFormat ( timeText , elem . dataset . timeformat ) ;
41+ elem . innerHTML = newTime ;
42+ elem . dataset . timeformat = curFormat ;
43+ }
44+ }
45+
46+ function getNewFormat ( timeString , curFormat ) {
47+ /*
48+ If curFormat is 12hr -> change to 24hr and vice versa
49+ */
50+ const re = / ( \d ? \d : \d \d ) ( a m | p m | A M | P M ) ? ( \( n e x t d a y \) ) ? / ;
51+ const parsed = timeString . match ( re ) ;
52+ if ( parsed ) {
53+ const hourMinArray = parsed [ 1 ] . split ( ":" ) ;
54+ let hour = parseInt ( hourMinArray [ 0 ] ) ;
55+ let postfix = "" ;
56+
57+ if ( parsed [ 2 ] || curFormat === "12hr" ) {
58+ if ( parsed [ 2 ] && parsed [ 2 ] . toLowerCase ( ) === "pm" ) {
59+ if ( hour !== 12 )
60+ hour += 12 ;
61+ }
62+ curFormat = "24hr" ;
63+ }
64+ else if ( curFormat === "24hr" ) {
65+ if ( hour === 24 ) {
66+ hour = 0 ;
67+ postfix = "am" ;
68+ }
69+ else if ( hour === 12 )
70+ postfix = "pm" ;
71+ else if ( hour > 12 ) {
72+ hour -= 12 ;
73+ postfix = "pm" ;
74+ }
75+ else
76+ postfix = "am" ;
77+ curFormat = "12hr" ;
78+ }
79+ const hourString = hour . toString ( ) . padStart ( 2 , '0' ) ;
80+ return [ hourString + ":" + hourMinArray [ 1 ] + postfix , curFormat ] ;
81+ }
82+ return [ timeString , curFormat ] ;
83+ }
3584
3685 /*
3786 Convert date time string into a format accepted by Date object
You can’t perform that action at this time.
0 commit comments