1

I want to combine String date("19801115") and String time("1530") into a single Instant datetime.

For example: There are two String variables:

String applicationDate = "19801115";
String applicationTime = "1530";

And combine them into the applicationDateTime(Instant type, ex: "1980-11-15T15:30:00Z"). How do I achieve that? Thanks.

william
  • 13
  • 3
  • 2
    Without at least showing us some code that tells us how those 2 objects are represented (Are they strings? java.util.date? java.time objects?) it is literally impossible to answer. – OH GOD SPIDERS Feb 05 '20 at 09:55
  • @OHGODSPIDERS, sorry and thanks for your feedback, I will make my question more clearly. – william Feb 05 '20 at 10:01
  • Neither of those is an "instant"; it looks like you have a `LocalDate` and `LocalTime`, which needs a time zone to be convertible to an instant. – chrylis -cautiouslyoptimistic- Feb 05 '20 at 10:08

1 Answers1

1
String dateString = "19801115";
String timeString = "1530";

Date date = null;
try {
    date = new SimpleDateFormat("yyyyMMddhhmm").parse(dateString + timeString);
} catch (ParseException e) {
    e.printStackTrace();
}
Instant reqInstant = date.toInstant();
System.out.println(reqInstant); // time here depends on your local settings, may differ from 15:30

// this way you adjust an Instant to a time zone you need
ZonedDateTime zdt = ZonedDateTime.ofInstant(reqInstant, ZoneId.systemDefault() /*<- needed time zone here*/);
System.out.println(zdt.toInstant()/*returns an Instant*/);

Additionally, similar functionality with DateTimeFormatter :

    String dateString = "19801115";
    String timeString = "1530";

    DateTimeFormatter dtf = new DateTimeFormatterBuilder()
            .appendPattern("yyyyMMddHHmm")
            .toFormatter()
            .withZone(ZoneId.systemDefault() /*<- needed time zone here*/);
    ZonedDateTime zdtOriginal = ZonedDateTime.parse(dateString + timeString, dtf);

    System.out.println(zdtOriginal.toInstant()/*returns an Instant*/);

    // this way you adjust an Instant to a time zone you need
    ZonedDateTime zdt = zdtOriginal.withZoneSameLocal(ZoneId.of("GMT") /*<- needed time zone here*/);
    System.out.println(zdt.toInstant()/*returns an Instant*/);
dimirsen Z
  • 873
  • 13
  • 16
  • 1
    Perhaps class [DateTimeFormatter](https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html) is more appropriate here, rather than class `SimpleDateFormat`? – Abra Feb 05 '20 at 10:53
  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. – Ole V.V. Feb 05 '20 at 13:36
  • 1
    added code snippet with `DateTimeFormatter` – dimirsen Z Feb 05 '20 at 15:07