Search code examples
javascriptarraysobjectutc

Detect day through UTC-5 and obtain variable value


Hello everyone have this variable in JavaScript

gateco = {
  "thursday": [{
    "open": "12:00",
    "close": "18:49"
  }],
  "friday": [{
    "open": "12:00",
    "close": "18:59"
  }]
};

How to get the day of UTC-5 time and access the open and close values respectively according to the day?


Solution

  • you can do that...
    see time zone list here

    const
      dateTimeOption =
        { timeZone : 'Etc/GMT+5'
        , hour12   : false
        , weekday  : 'long'
        , hour     : '2-digit'
        , minute   : '2-digit' 
        }
    , gateco =
        { thursday : [ { open: '12:00', close: '18:49' } ]  // why is it an Array ?
        , friday   : [ { open: '12:00', close: '18:59' } ] 
        } 
    
    let isOpenNow  = false
      , [wDay,h,m] = new Intl.DateTimeFormat('en-US', dateTimeOption)
                      .format(new Date())
                      .split(/:| /)
                      .map(s=>Number(s)||s.toLowerCase() )                  
    
    if ( gateco[wDay] )
      {
      let hm = (h *100) +m // simplied for comparing 
        , h_m_Open  = gateco[wDay][0].open
                        .split(':')
                        .reduce((hm,t,i)=>hm + (!i?100:1)*Number(t) ,0)
        , h_m_Close = gateco[wDay][0].close
                        .split(':')
                        .reduce((hm,t,i)=>hm + (!i?100:1)*Number(t) ,0)
    
      isOpenNow = (h_m_Open <= hm  && hm <= h_m_Close)
      }             
    //console.log( wDay,h,m )
    console.log( 'isOpenNow = ', isOpenNow)