Friday 10 April 2020

Format Instant to String

Using DateTimeFormatter, you can format an Instant object.

Step 1: Get the instance of DateTimeFormatter.
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.GERMANY).withZone(ZoneOffset.UTC);

Step 2: Use format method of DateTimeFormatter to get the formatted output of Instant.
Instant instant = Instant.now();
String formattedStr = formatter.format( instant );

App.java
package com.sample.app;

import java.time.Instant;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.util.Locale;

public class App {

 public static void main(String args[]) {
  DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG).withLocale(Locale.GERMANY)
    .withZone(ZoneOffset.UTC);
  
  Instant instant = Instant.now();
  String formattedStr = formatter.format( instant );

  System.out.println("formatter : " + formatter);
  System.out.println("instant : " + instant);
  System.out.println("formattedStr : " + formattedStr);
 }
}

Output
formatter : Localized(LONG,LONG)
instant : 2020-02-24T04:50:01.964Z
formattedStr : 24. Februar 2020 10:20:01 IST


You may like
Previous                                                    Next                                                    Home

No comments:

Post a Comment