0

I want to get the date data from the database as "dd.mm.mm.yyyy HH:mm". How can I convert this data with Javascript?

Normally the date data comes as follows,

2023-08-14T15:20:59.659667+03:00

The format I want it to be,

14.08.2023 20:59

Js code side,

tablerow = $('<tr/>');
tablerow.append(`<td class="border-bottom-0">${value.createDate}</td>`);

Can you help me? Thanks,

I did not encounter any errors.

gkmnada
  • 64
  • 6
  • Does this answer your question? [How do I format a date in JavaScript?](https://stackoverflow.com/questions/3552461/how-do-i-format-a-date-in-javascript) – phuzi Aug 16 '23 at 11:05

2 Answers2

1

Try This:

    // Input date string 
    const inputDate = '2023-08-14T15:20:59.659667+03:00'; // Declare this to get Date from your DB. 
    
    // Create a new Date object from the input date string
    const date = new Date(inputDate);

    // Format the date as "dd.mm.yyyy HH:mm"
    const formattedDate = `${('0' + date.getDate()).slice(-2)}.${('0' + (date.getMonth() + 1)).slice(-2)}.${date.getFullYear()} ${('0' + date.getHours()).slice(-2)}:${('0' + date.getMinutes()).slice(-2)}`;

    console.log(formattedDate); 
HamiD
  • 1,075
  • 1
  • 6
  • 22
  • First of all, thank you, This works to bring the current date, but how can I convert the format of the date in the database? This is the format in the database `2023-08-14T15:20:59.659667+03:00` – gkmnada Aug 16 '23 at 10:53
  • I just edited the code – HamiD Aug 16 '23 at 11:01
  • 1
    If your input Date from Databse isnt String, you have to replace it using this code: const inputDate = String(dataFromTheServer) – HamiD Aug 16 '23 at 11:06
  • Thank you very much, I can get it in the format I want now. – gkmnada Aug 16 '23 at 11:12
1

You can use this function to format the date:

function formatDate(dateToFormat) {
  const date = new Date(dateToFormat);

  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = date.getHours();
  const minutes = date.getMinutes();

  return `${day}.${month}.${year} ${hours}:${minutes}`;
}

Note: dateToFormat should be in string format