moment().fromNow() ignores UTC

Viewed 148

I've seen multiple questions around this and this post did not clarify it for me.

I must add to the expression of confusion around the UTC functionality. The most intuitive expectation of moment.utc() would be that it would return a Moment object representing the now date/time in UTC time. But according to this discussion it's not the case and it just sets the flag. It still unclear what that flag does. None of this is mentioned in the documentation, which makes it woefully inadequate. Please add clarification of this topic with examples to your backlog. Thank you.

I get ISO 8601 time from a query and want to display that result different depending on user config in a datagrid.

I have tried different methods both from documentation and stackoverflow, but none seems to give the expected result, which would be UTC-time fromNow(), but instead shows local time fromNow(). In console the values seems right until moment.fromNow()

// Changes value on item["StartTime"] based on user config before it pushed. 
                else {
                    let time = item["StartTime"] // Outputs ISO 8601
                    console.log(time) // Output 2021-02-16T12:40:56.790Z
           
 switch (true) {

              // This case is the problem 
       case (userConfig.general.dateFormat == "From now" && 
             userConfig.general.useLocal == false): 

             var utcDate = new Date(time).toUTCString();
             // output Tue, 16 Feb 2021 12:40:56 GMT

             utcDate = moment.utc(utcDate).fromNow();
             // output In an hour
             // Im in UTC+1

             item["StartTime"] = utcDate
             break; 


       case (userConfig.general.dateFormat == "From now" && 
             userConfig.general.useLocal == true):
             time = new Date(time)        // Outputs date 
             object defaults to browser timezone 
             time = moment(time).locale(navigator.language).fromNow()
             time = time.toLocaleString(navigator.language) 
             item["StartTime"] = time
             break;
       case (userConfig.general.dateFormat == "Timestamp" && userConfig.general.useLocal == true):
             time = new Date(time)        // Outputs date object defaults to browser timezone 
             time = time.toLocaleString(navigator.language) 
             item["StartTime"] = time
             break;
      case (userConfig.general.dateFormat == "Timestamp" && userConfig.general.useLocal == false):
             let date = moment(time);
             let dateComponent = date.utc().format('YYYY-MM-DD');
             let timeComponent = date.utc().format('HH:mm:ss');
             item["StartTime"] = dateComponent + " " + timeComponent
             break;
                    }  
0 Answers
Related