Link to home
Start Free TrialLog in
Avatar of pamela rizk
pamela rizkFlag for Lebanon

asked on

convert string to datetime in javascript

dear All

i have a string in javascript as below :
11/04/2019 17:30:00 (that represents month/day/year   and time )
i need to  convert this string to a datetime with the below format:
2019-11-04T17:30:00+02:00

how to do that ?
Avatar of leakim971
leakim971
Flag of Guadeloupe image

a = new Date("11/04/2019 17:30:00");
a.toISOString();

Open in new window


User generated image
You mean this?
Expected format: 2019-11-04T17:30:00+02:00 - but I expect +01:00 since it is not DST

https://jsfiddle.net/mplungjan/ot0xmh9s/

const pad = num => ("0" + num).slice(-2);

const getFormattedDate = d => {
  const tzOffsetMin = d.getTimezoneOffset(),
    offsetHours = Math.floor(Math.abs(tzOffsetMin / 60)),
    offsetMin = Math.abs(tzOffsetMin % 60);
  let sign = "";
  if (tzOffsetMin < 0) sign = "+"; // opposite of what we should think
  else if (tzOffsetMin > 0) sign = "-";

  // we could steal the time from the toString and replace / GMT/,""

  return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())}` +
    `T${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}` +
    `${sign}${pad(offsetHours)}:${pad(offsetMin)}${sign===""?"Z":""}`;
}

Open in new window

Avatar of pamela rizk

ASKER

Expected format: 2019-11-04T17:30:00+02:00
but what i am getting from your solution is
2019-11-04T16:30:00-01:00
why?
time is 16:30 instead of 17:30 why?please explain
yes better to have another solution for that
something more global and not specific
in all cases thank you
Please see my updated answer.
I have written a function instead.
I still expect +01:00 and not +02:00 in Amsterdam in November
something more global and not specific

That +02:00 is your original post is specific to YOUR timezone
What I post is the UTC + 00:00 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
You want +02:00 ?

a = new Date("11/04/2019 17:30:00");
a.setHours(a.getHours() + 2);
var d = a.toISOString().split(".")[0] + "+02:00"

Open in new window


User generated image
That would fail across daylight saving
ASKER CERTIFIED SOLUTION
Avatar of pamela rizk
pamela rizk
Flag of Lebanon image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi Pamela

Great you found a solution you could use.

But you did not actually use the answer you accepted as solution?