enes

Enes Altınkaya

How to Format Localdatetime in Java

How to Format Localdatetime in Java

Parsing and Formatting LocalDateTime

  • You can format LocalDateTime in Java using the following code snippet.
package enesaltinkayacom;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

public class Test {
    public static void main(String[] args) {
        // If you want to use UTC timezone.
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        String formattedDate = format(LocalDateTime.now());
        System.out.println(formattedDate);
    }

    public static String format(LocalDateTime localDateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(formatter);
    }
}

  • To parse a LocalDateTime, use the following.
package enesaltinkayacom;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

public class Test {
    public static void main(String[] args) {
        // If you want to use UTC timezone.
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        LocalDateTime localDateTime = parse("2018-02-27 10:13:20");
        System.out.println(localDateTime);
    }

    public static LocalDateTime parse(String dateString) {
        DateTimeFormatter formatter =
                DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return LocalDateTime.parse(dateString, formatter);
    }
}

Parsing and Formatting java.util.Date

  • Format java.util.Date.
package enesaltinkayacom;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class Test {
    public static void main(String[] args) {
        // If you want to use UTC timezone.
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        Date now = Calendar.getInstance().getTime();
        String formattedDate = format(now);
        System.out.println(formattedDate);
    }

    public static String format(Date date) {
        SimpleDateFormat formatter =
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.format(date);
    }
}
  • Parse a string to java.util.Date.
package enesaltinkayacom;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class Test {
    public static void main(String[] args) throws ParseException {
        // If you want to use UTC timezone.
        TimeZone.setDefault(TimeZone.getTimeZone("GMT"));
        String dateString = "2018-02-27 10:22:20";
        Date date = parse(dateString);
        System.out.println(date);
    }

    public static Date parse(String dateString) throws ParseException {
        SimpleDateFormat formatter =
                new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return formatter.parse(dateString);
    }
}
Share on