user2358262
user2358262

Reputation: 257

Convert a given date to UTC date time

How can I covert a given date to a UTC start date time and end date time.

String date = "2017-01-01"
//Needed startDate as 2017-01-01T00:00:00Z
//and end date as 2017-01-01T23:59:59Z

Upvotes: 1

Views: 6825

Answers (2)

ujulu
ujulu

Reputation: 3309

The question is actually answered using Java 8 feature. But if you're like me and sitting on the older versions of Java, the following might serve the purpose even though it is not as elegant as the other solution:

    String dateString = "2017-01-01"; 
    final SimpleDateFormat sdfInput = new SimpleDateFormat("yyyy-MM-dd");
    // we need Calendar to manipulate date components
    Calendar cal = new GregorianCalendar();
    cal.setTime(sdfInput.parse(dateString));
    
    final SimpleDateFormat sdfOutput = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    String startDate = sdfOutput.format(cal.getTime());
    
    cal.set(Calendar.HOUR, 23);
    cal.set(Calendar.MINUTE, 59);
    cal.set(Calendar.SECOND, 59);
    String endDateString = sdfOutput.format(cal.getTime());
    
    System.out.println(startDate);
    System.out.println(endDateString);

The output:

2017-01-01T00:00:00Z

2017-01-01T23:59:59Z

Upvotes: 0

Daniel Bubenheim
Daniel Bubenheim

Reputation: 4229

It depends on your java version and as always there are many ways to solve this. With java 8 in place you can do something like this:

First you need to parse the date into a java.time.LocalDate

String date = "2017-01-01";
final LocalDate localDate = LocalDate.parse(date);
System.out.println(localDate);

Which prints

2017-01-01

From this LocalDate you can create your UTC start and end dates as types of java.time.ZonedDateTime as follows

final ZoneId utc = ZoneId.of("UTC");
final ZonedDateTime start = LocalDate.parse(date).atStartOfDay(utc);
final ZonedDateTime end = LocalDate.parse(date).atTime(23, 59, 59).atZone(utc);
System.out.println(end); 

This prints

2017-01-01T00:00Z[UTC]
2017-01-01T23:59:59Z[UTC]

Notice for the end date you could also do

final ZoneId utc = ZoneId.of("UTC");
final ZonedDateTime end = LocalDate.parse(date).atTime(LocalTime.MAX).atZone(utc);

Which gives you a few more digits

2017-01-01T23:59:59.999999999Z[UTC]

See also

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html https://docs.oracle.com/javase/8/docs/api/java/time/ZonedDateTime.html

Hope it helps!

Upvotes: 1

Related Questions