1

Input: I have a date string: "2018-11-30T01:00:00+11:00"

Usecase: I need to convert it into Date object using plain js or with any library.

Result: I should receive a date object with date part as "2018-11-30" and time part as "1:00".

Please help. I've tried every solution but the time always changes to match my machine's timezone. I don't want that behavior neither do I want to do complicated time conversions on my backend.

saran3h
  • 12,353
  • 4
  • 42
  • 54
  • 2
    Omg thanks man. BTW the accepted answer is wrong! it's the 2nd answer that deserve a medal. I'm going to post it as an answer here. – saran3h Nov 13 '18 at 13:35
  • glad to know that's worked for you! – OliverRadini Nov 13 '18 at 13:44
  • @OliverRadini scratch that. it wasn't a full proof solution either. After spending some more time, I came up with the solution posted below. – saran3h Nov 13 '18 at 18:14

1 Answers1

0

This is the solution that I came up with for this problem which actually works.


library used: momentjs with plain javascript Date class.

Step 1. Convert String date to moment object (PS: moment retains the original date and time as long as toDate() method is not called):

const dateMoment = getMomentFromIsoString(date);

Step 2. Extract hours and minutes values from the previously created moment object:

  const hours = dateMoment.hours();
  const mins = dateMoment.minutes();

Step 3. Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):

  const dateObj = dateMoment.toDate();

Step 4. Manually set the hours and minutes extracted in Step 2.

  dateObj.setHours(hours);
  dateObj.setMinutes(mins);

Step 5. dateObj will now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.

Hope this helps.

saran3h
  • 12,353
  • 4
  • 42
  • 54