date-fns | How do I format to UTC

后端 未结 5 573
逝去的感伤
逝去的感伤 2020-12-17 10:42

Problem

It looks like when I use the format() function, it automatically convert the original UTC time into my timezone (UTC+8). I have been digging t

5条回答
  •  失恋的感觉
    2020-12-17 11:01

    Note
    The following solution will not work for all time zones, so if timezone accuracy is critical for your application you might want to try something like the answer from Beni. See this link for more info

    I had the exact same question today and did some research to see if anyone has come up with anything better since this question was posed. I came across this solution which fit my needs and stylistic preference:

    import { format, addMinutes } from 'date-fns';
    
    function formatDate(date) {
      return format(addMinutes(date, date.getTimezoneOffset()), 'yyyy-MM-dd HH:mm:ss');
    }
    

    Explanation

    getTimezoneOffset returns the number of minutes needed to convert that date to UTC. In PST (-0800 hours) it would return 480 whereas for somebody on CST (+0800 hours) it would return -480.

提交回复
热议问题