Home > Back-end >  How to convert Reactjs DateTimePicker date time convert to Java OffsetDateTime or LocalDateTime
How to convert Reactjs DateTimePicker date time convert to Java OffsetDateTime or LocalDateTime

Time:07-22

My frontend ReactJs code snippet:-

import React, { useState } from 'react';
import DateTimePicker from 'react-datetime-picker';
import './App.css';

function App() {

  const [value, onChange] = useState(new Date());

  console.log("onChage: " value);

  return (
    <div className="App">
      <DateTimePicker
        onChange={onChange}
        value={value}
        format={'dd/mm/yyyy hh:mm'}
      />
    </div>
  );
}

export default App;

I can see console log as

onChage: Thu Jul 21 2022 13:11:32 GMT 0300 (Eastern European Summer Time)

I need to send this date time to Java Spingboot backend. For the backend I need to convert this date time to OffsetDateTime or LocalDateTime. How can I convert this?

Updated:

I tried and managed to convert to Data. By this:-

String dateStr = "Thu Jul 21 2022 13:11:32 GMT 0300 (Eastern European Summer Time)";
String[] tokens = dateStr.split("GMT");
String dateTimeStr = "";
if (tokens.length == 2){
    dateTimeStr = tokens[0].trim();
}
System.out.println(dateTimeStr);
SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss", Locale.ENGLISH);

Date date = formatter.parse(dateTimeStr);
String formattedDateString = formatter.format(date);
System.out.println("date: " formattedDateString);

There I lost time zone and offset. How do I keep the time zone and offset GMT 0300 (Eastern European Summer Time)?

CodePudding user response:

After the comment by Ole V.V. I mangaged to get both OffsetDateTime and ZonedDateTime. I am sharing the soluion. All credit goes to Ole V.V. Thanks a lot Ole V.V.

String dateStr = "Thu Jul 21 2022 13:11:32 GMT 0300 (Eastern European Summer Time)";

DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("EEE MMM d yyyy HH:mm:ss 'GMT'XX (zzzz)", Locale.ROOT);
OffsetDateTime date1 = OffsetDateTime.parse(dateStr, dateTimeFormatter);
System.out.println(date1);
// print 2022-07-21T13:11:32 03:00


ZonedDateTime zdt = ZonedDateTime.parse(dateStr, dateTimeFormatter.withZone(ZoneId.systemDefault()));
System.out.println(zdt);
 // print 2022-07-21T13:11:32 03:00[Europe/Bucharest]

CodePudding user response:

Simplest way to do is just do this :-

String timeString = input.substring(4,24);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM dd YYYY HH:mm:ss");
System.out.println(LocalDateTime.parse(timeString, formatter);
  • Related