0

I need to get the current date but I can't figure out how to format it the way I need. Every method Ive found separates the values with - and i need them separated with /.

Ive tried doing it the long way like:

const today = new Date();
let dd = today.getDate();

let mm = today.getMonth()+1; 
const yyyy = today.getFullYear();
if(dd<10) 
{
    dd='0'+dd;
} 

if(mm<10) 
{
    mm='0'+mm;
} 

today = yyyy+'/'+mm+'/'+dd;

This works but it is messy and causes some TS errors as the values are numbers and Im treating them like strings. Ive also tried

const date = new Date().toISOString().split(“T”)[0];

Which gives me the date in the correct order but separated by - is there any method that will format the current date separated by /?

CourtneyJ
  • 458
  • 6
  • 19

1 Answers1

0

This should work

const date = new Date().toISOString().split("T")[0].replaceAll("-", "/");
Souvik Nandi
  • 354
  • 2
  • 6
  • That shows the UTC date which is different to the local date for the period of the local timezone offset at the start or end of the day depending on whether the offset is positive or negative respectively. – RobG Jun 04 '21 at 20:37
  • @RobG correct if you want to get date based on time zone, but if you check the question it is solely based on formatting and without the context where date is used we do not know whether it requires local or GMT. Generally if we store in DB or in case where users are across many timezones it is preferred to store it in GMT for easy reference. On server side it is always recommended to use GMT time, if it is for client side or anything that requires local timezone reference then your recommendation is totally justified. – Souvik Nandi Jun 05 '21 at 08:24
  • The OP uses only local methods except for *toISOString* so likely local is required. At the very least your answer should include advice regarding the difference. – RobG Jun 05 '21 at 08:55