skip to Main Content

I have an ISO date which is stored as a string. I want to get only the hours part as is. The below code does not work. So, how do I make it work using dayjs?

function getHours(date:string){
 const hour : dayjs(date).hour();
 console.log(hour);
}

getHours("2023-05-06T08:00:00Z");//Expected 8, but got 1.

2

Answers


  1. In dayjs you need to use the utc plugin:

    var dayjs = require("dayjs")
    var utc   = require("dayjs/plugin/utc")
    
    dayjs.extend(utc);
    
    function getHours(date){
     const hour = dayjs.utc(date).hour();
     return hour;
    }
    
    getHours("2023-05-06T08:00:00Z"); // 8
    
    Login or Signup to reply.
  2. You have a string with a specific format and you want a substring. Using a date library like dayjs or even built-in Date would be overkill. Get the substring and optionally convert it to a number:

    function getHours(date){
      console.log(date.substr(11, 2));
      console.log(+date.substr(11, 2));
    }
    
    getHours("2023-05-06T08:00:00Z");

    No plugins, no external libraries and only one conversion from string to number required.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search