简体   繁体   中英

How to convert Reactjs DateTimePicker date time convert to Java OffsetDateTime or LocalDateTime

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)?

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);

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM