Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Date.toLocaleString does not work properly

So i am setting up an api that sends me an email on user submission

It adds a date to the email as such

const date = new Date().toLocaleString("en-GB", {
    timeZone: "Europe/Athensli",
  });
  const mailMe = {
    from: process.env.EMAIL,
    to: process.env.MYEMAIL,
    subject: "New Message",
    html: `<p>Name: ${name}</p>
        <p>Date: ${date}</p>
        <p>Email: ${email}</p>
        <p>Company: ${company}</p>
        <p>Message: ${message}</p>`,
  };

The thing is, the email comes with everything looking good but "undefined" in the date field

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Running the line in node terminal returns


>let dt = new Date().toLocaleString("en-GB", {timezone: "Europe/Athens",}); console.log(dt);
18/09/2023, 12:29:32
undefined

While "new Date().toLocaleString("en-GB", {timezone: "Europe/Athens",});" by itself returns the expected
’18/09/2023, 12:29:32′

Can anyone help me understand what i am missing?

As far as looking it up goes it should be ok as is.

>Solution :

The undefined returned by a Node terminal is coming from the console.log() call itself. The first line contains the printed value which is 18/09/2023, 12:29:32, and the second line is a value returned by the .log() method which is indeed undefined because console.log() does not return anything special.

If you want to check the value of the dt variable in the Node terminal, just type

> dt
'18/09/2023, 12:29:32'

console.log() will always add undefined.


And as for the first issue, you have a typo

timeZone should be timezone.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading