sandy
sandy

Reputation: 303

defaultValue of showTime attribute in antd datePicker couldn't set the time

I'm using ant design for my react hook based development. I am retrieving date from database over a network call and the date retrieved from database is look like "2020-09-01T05:02:00.000+0000". It is a string. I have to parse this date and show the date value and time value through antd datePicker in my page. Though I've success with setting up date part but I'm stuck with setting up the time. Here is my code,

########### Here is my datepicker ###########

                          <DatePicker
                            name="Campaign-date"
                            defaultValue={moment(formData['Campaign-date'].split('T')[0])}
                   
                            showTime={{
                                defaultValue: moment(formData['Campaign-date'].split('T')[1],'HH:mm'),
                                format: 'HH:mm'
                                
                            }}
                            format={'YYYY-MM-DD HH:mm'}
                            style={{ width: '100%' }}
                            onChange={handleDateChange}
                        />

########################## Here is my handleDateChange function ##########################

const handleDateChange = date => {
    setFormdata({
        ...formData,
        'Campaign-date': date
            .format('YYYY-MM-DD HH:mm')
            .split(' ')
            .join('T')
    });
};

formData['Campaign-date'] is the date retrieved from the database. I feel the showTime attribute is not working as expected. I want to get a result of "05:02" but instead the value shown is, "00:00".

I have tried different variation in showTime such as,

defaultValue: moment('05:02','HH:mm'),
//or
defaultValue: moment(formData['Campaign-date'],'HH:mm')
//or
defaultValue: moment(formData['Campaign-date'].split('T')[1].split('.),'HH:mm')

but nothing is working. It is always setting the value as "00:00". And I have no problem with my onChange functionality. It is working perfect. The date/time change code wise working as expected. It is just the view on my page is not showing correct time.

I'm really stuck with. Any help therefore, is much appreciated.

Upvotes: 0

Views: 7332

Answers (2)

pilchard
pilchard

Reputation: 12956

Ant Design DatePicker:

(sandbox)

import React from "react";
import ReactDOM from "react-dom";
import { DatePicker, Space } from "antd";
import moment from "moment";

import "./index.css";
import "antd/dist/antd.css";

const initialState = {
  data1: "form field",
  data2: "form field 2",
  "Campaign-date": "2020-09-01T05:02:00.000+0000"
};

function FormComponent() {
  const [formData, setFormData] = React.useState(initialState);

  console.log(formData);

  function onChange(value, dateString) {
    if (value) {
      setFormData({
        ...formData,
        "Campaign-date": value.toISOString(true)
      });
    }
    //console.log("Selected Time: ", value); //Moment object
    //console.log("Formatted Selected Time: ", dateString); //String
  }

  return (
    <Space direction="vertical" size={12}>
      <DatePicker
        name="Campaign-date"
        defaultValue={moment(formData["Campaign-date"], "YYYY/MM/DD HH:mm")}
        format={"YYYY/MM/DD HH:mm"}
        showTime={{ format: "HH:mm" }}
        onChange={onChange}
      />
      <div style={{ marginTop: 16 }}>
        Selected Date:{" "}
        {formData["Campaign-date"]
          ? moment(formData["Campaign-date"]).format("YYYY-MM-YY HH:mm")
          : "None"}
      </div>
    </Space>
  );
}

ReactDOM.render(<FormComponent />, document.getElementById("container"));

If you are using react-datepicker 2.0 or up, you need to use a javascript Date object. Here is a working setup.

  function parseISOString(s) {
    var b = s.split(/\D+/);
    return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
  }

  const isoString = '2020-09-01T05:02:00.000+0000';
  const dateFromISOString = parseISOString(isoString);
  
  <DatePicker
    selected={dateFromISOString}
    dateFormat="dd/MM/yyyy HH:mm"
    showTimeSelect
    timeFormat="HH:mm"
    timeIntervals={15}
    placeholderText="Select date"
    onChange={handleChange}
  />

Overview

The string you are receiving from the database is an ISO date string.

You can use moment.js to easily parse it or parse it manually and create a new Date object from it. Here is a snippet illustrating both. The Date example uses this answer: Change ISO Date String to Date Object - JavaScript

const isoString = "2020-09-01T05:02:00.000+0000"

// with Moment
console.log("With Moment");
const timeFromMoment = moment(isoString).format("HH:mm");
console.log(timeFromMoment);

// with Date
console.log("With Date");
// https://stackoverflow.com/questions/27012854/change-iso-date-string-to-date-object-javascript
function parseISOString(s) {
  var b = s.split(/\D+/);
  return new Date(Date.UTC(b[0], --b[1], b[2], b[3], b[4], b[5], b[6]));
}

const dateFromISOString = parseISOString(isoString);
console.log(dateFromISOString);

// return Local adusted time
const localHours = dateFromISOString.getHours();
console.log(localHours);

// return UTC time
const utcHours = dateFromISOString.getUTCHours();
console.log(utcHours);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.27.0/moment.min.js"></script>

Upvotes: 1

sazzad
sazzad

Reputation: 525

<DatePicker
      name="Campaign-date"
      defaultValue={moment(formData['Campaign-date'].split('T')[0])}
               
      showTime={{
              defaultValue: moment(formData['Campaign-date'].split('T')[1].split('.')[0],'HH:mm:ss'),
              format: 'HH:mm:ss'
                            
                        }}
      format={'YYYY-MM-DD HH:mm'}
      style={{ width: '100%' }}
      onChange={handleDateChange}
      />

Upvotes: 0

Related Questions