0

I am working with java 8. I receive a date string such as "2019-01-01" and I have to translate this into an UTC long. I cannot convert it into a date first, because it is converted to the local timezone.

So in entry I have "2019-01-01" and in exit I need 1546300800000

I need to do this in one line (working with talend...)

Any help is welcome.

liamhawkins
  • 1,301
  • 2
  • 12
  • 30
spr654
  • 11
  • 1
  • 1
    @OleV.V. it's arguably best not to point new users towards that duplicate as the answers are using the old Java date classes which shouldn't be encouraged. – DodgyCodeException Mar 08 '19 at 11:36
  • 1
    In the linked original question (found a new one, @DodgyCodeException) please ignore the (many) answers using `SimpleDateFormat` and `Date` since those classes are poorly designed and long outdated, the former in particular notoriously troublesome. I am fond enough of [my own answer](https://stackoverflow.com/a/47429283/5772882) to recommend it. – Ole V.V. Mar 08 '19 at 12:00

2 Answers2

3

Is this what you were looking for?

import java.time.LocalDate;
import java.time.ZoneId;

// one class needs to have a main() method
public class HelloWorld
{
  // arguments are passed using the text field below this editor
  public static void main(String[] args)
  {

    String strDate = "2019-01-01";

    LocalDate localDate = LocalDate.parse(strDate);

    // Replace <Continent> and <City> with correct values such as: Europe/Paris
    // ZoneId zoneId = ZoneId.of("<Continent>/<City>"); 
    ZoneId zoneId = ZoneId.systemDefault(); 

    ZonedDateTime zdt = localDate.atStartOfDay(zoneId);
    long epoch = zdt.toEpochSecond();

    System.out.println(epoch);
  }
}

Note: This also works if you use LocalDateTime

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
acarlstein
  • 1,799
  • 2
  • 13
  • 21
  • Hi,thanks for your answer. The solution gives me compilation errors. I got the final solution from somewhere else: long epoch =LocalDate.parse(strDate, DateTimeFormatter.ISO_LOCAL_DATE).atStartOfDay(ZoneId.of("UTC")).toInstant().toEpochMilli(); – spr654 Mar 07 '19 at 16:21
  • 1
    @spr654 what compilation error do you get? The only "error" in this answer is the use of `Zone` instead of `ZoneId` in the commented line. Everything else works. – DodgyCodeException Mar 07 '19 at 16:49
  • @spr654 Sorry about that. When I was writing the answer, I got a meeting coming up. I tested and updated the code I shared, take a look again. Anyways, I am glad you made it work. – acarlstein Mar 07 '19 at 17:54
1

In one (longish) line as requested:

long t = LocalDate.parse("2019-01-01").atStartOfDay(ZoneOffset.UTC).toInstant().toEpochMilli();

The logic is the same as in the very good answer by acarlstein except he get seconds since the epoch (1 546 300 800), I get milliseconds (1 546 300 800 000).

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161