skip to Main Content

I have a date time in string in this ISO format:

2023-08-07T09:38:43+07:00

but now I need to convert it to YYYYMMDDHHmmss format, so I expect I will get this string

20230807093843

how to do that using Javascript without using Moment or another libarary?

2

Answers


  1. Here this is one way of doing it I guess.

       
    const originalDate = "2023-08-07T09:38:43+07:00";
    
    // Parse the original date string
    const parsedDate = new Date(originalDate);
    
    // Extract individual components
    const year = parsedDate.getFullYear();
    const month = (parsedDate.getMonth() + 1).toString().padStart(2, '0');
    const day = parsedDate.getDate().toString().padStart(2, '0');
    const hours = parsedDate.getHours().toString().padStart(2, '0');
    const minutes = parsedDate.getMinutes().toString().padStart(2, '0');
    const seconds = parsedDate.getSeconds().toString().padStart(2, '0');
    
    // Create the final formatted date string
    const formattedDate = `${year}${month}${day}${hours}${minutes}${seconds}`;
    
    console.log(formattedDate); // Output: 20230807093843
    Login or Signup to reply.
  2. Slice the string and then replace the undesired characters:

    const formatted = "2023-08-07T09:38:43+07:00".slice(0, 19).replaceAll(/[-:T]/g, "");
    
    console.log(formatted === "20230807093843"); // true
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search