'How to concat date picker value and time picker value in single element?

I am using date picker and time picker seperatly in my vue.js code(using element.io) my datepicker and time picker giving me value as : date = ""2018-01-19T00:00:00.000Z" time = "2018-05-20T00:06:30.000Z Both date and time are of object form... now I want to create new object dataTime = "2018-01-19T00:06:30.000Z"

how to create this and then convert it to ISOStrinh format?



Solution 1:[1]

You can use date-fns as follows:

import {formatISO} from 'date-fns';

const date = new Date();
const time = new Date();
const newDate = formatISO(date, {representation: 'date'});
const newTime = formatISO(time, {representation: 'time'});
const dateTime = `${newDate}T${newTime}`

Solution 2:[2]

You can do it in plain Javascript, no need for a library like moment.js.

Here is a verbose example it can be simplified...

getDateTime($d,$t){
   let date = $d; //i.e. "2018-01-19T00:00:00.000Z";
   let time = $t; //i.e. "2018-05-20T00:06:30.000Z";

   date = date.split('T').slice(0,1);
   time = time.split('T').slice(1);

   return date + 'T' + time;
}

Solution 3:[3]

Most answers here do not take daylight savings into account. Concatenating date and time with T will give you an incorrect result if the date and time are not in the same daylight savings rule. Your time will be an hour off, depending on the timezone rules. Here's a simple way to avoid daylight savings issues:

const mergeDateAndTime = (date, time) => {
  const newDate = new Date(date);

  newDate.setHours(time.getHours());
  newDate.setMinutes(time.getMinutes());
  newDate.setSeconds(time.getSeconds());
  newDate.setMilliseconds(0);

  return newDate;
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David Leuliette
Solution 2 skribe
Solution 3 robrechtme