skip to Main Content

I use dayjs in my typescript/javascript code. I want to convert a DayJs date into the below format. How to do it?

2020-04-25T00:00:00+00:00

Here is what I tried –

dayjs().format('YYYY-MM-DD hh:mm:ss Z');

But, it gives dates which look different from my desired format. For example –

2020-04-25T00:00:00.000Z

2

Answers


  1. To format string to show plus sign in DayJS you can use the format string YYYY-MM-DDTHH:mm:ssZ, where T is a literal string "T" that separates the date and time, and Z represents the timezone offset in the format ±hh:mm. Let me know if this code works for you.

    const date = dayjs(); // replace with your DayJS date object
    const formattedDate = date.format('YYYY-MM-DDTHH:mm:ssZ');
    console.log(formattedDate); // prints something like 2020-04-25T00:00:00+00:00
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.7/dayjs.min.js"></script>
    Login or Signup to reply.
  2. Don’t need any 3rd party Date library. Use native Intl.DateTimeFormat.

    Intl.DateTimeFormat.prototype.formatToParts()

    Below is an example of how to use this method. You will need to modify it to get your desired outcome:

    function format(dateObject){
    
        let dtf = new Intl.DateTimeFormat("en-US", {
        year: 'numeric',
        month: 'numeric',
        day: 'numeric',
        hour: 'numeric',
        minute: 'numeric',
        second: 'numeric'
      });
      
      var parts = dtf.formatToParts(dateObject);
      var fmtArr = ["year","month","day","hour","minute","second"];
      var str = "";
      for (var i = 0; i < fmtArr.length; i++) {
        if(i===1 || i===2){
          str += "-";
        }
        if(i===3){
           str += " ";
        }
        if(i>=4){
          str += ":";
        }
        for (var ii = 0; ii < parts.length; ii++) {
        let type = parts[ii]["type"]
        let value = parts[ii]["value"]
          if(fmtArr[i]===type){
            str = str += value;
          }
        }
      }
      return str;
    }
    console.log(format(Date.now()));
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search