Jon
Jon

Reputation: 453

How do I get my hour, minutes, seconds, and milliseconds to be zeros?

I'm trying to get my format to be 2016-07-08T00:00:00.000Z.

String myDate = "20160708";
LocalDate myLocalDate = LocalDate.parse(myDate, DateTimeFormatter.BASIC_ISO_DATE);
OffsetDateTime myOffsetDate = myLocalDate.atTime(OffsetTime.now(ZoneOffset.UTC));

System.out.println(myOffsetDate); //2016-07-08T14:58:23.170Z

Upvotes: 8

Views: 8357

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502845

Well don't say "I want it to use the current time"! That's what this is doing:

OffsetTime.now(ZoneOffset.UTC)

If you just want an OffsetDateTime from a LocalDate by providing a zero offset and midnight, you can use:

OffsetDateTime myOffsetDate = myLocalDate
    .atTime(LocalTime.MIDNIGHT)
    .atOffset(ZoneOffset.UTC);

Or if you prefer:

OffsetDateTime myOffsetDate = myLocalDate
    .atTime(OffsetTime.of(LocalTime.MIDNIGHT, ZoneOffset.UTC));

(Personally I prefer the first version, myself...)

Note that that's just getting you the right OffsetDateTime. If you want to format that with milliseconds and seconds, you'll need to do that explicitly:

DateTimeFormatter formatter = DateTimeFormatter
    .ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
System.out.println(myOffsetDate.format(formatter));

As noted in comments, if you're find with a ZonedDateTime instead of an OffsetDateTime, you can use

ZonedDateTime myOffsetDate = myLocalDate.atStartOfDay(ZoneOffset.UTC);

Upvotes: 9

Naresh Yadav
Naresh Yadav

Reputation: 713

I am not quite sure if you can get the ISO_INSTANCE date format with the given string using LocalDate. but you can use below java 8 piece of code to get the required format.

public String getISO_8601DateFormat(String yyyyMMdd){
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
    String requiredFormat = null;
    try {
        Date inputDate = sdf.parse(yyyyMMdd);
        long dateLongRepresentation = inputDate.getTime();
        long myTimeZoneOffset = TimeZone.getTimeZone(ZoneId.systemDefault()).getOffset(inputDate.getTime());
        Instant instance = Instant.ofEpochMilli(dateLongRepresentation + myTimeZoneOffset);
        requiredFormat = instance.toString();

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return requiredFormat;
}

Enjoy coding with java :)

Upvotes: 0

Related Questions