如何在 Java 中格式化日期和时间

x33g5p2x  于2021-10-16 转载在 Java  
字(2.1k)|赞(0)|评价(0)|浏览(353)

在本文中,您将学习如何将使用 Date、LocalDate、LocalDateTime 或 ZonedDateTime 表示的日期和时间格式化为 Java 中的可读字符串。

使用 DateTimeFormatter 格式化 LocalDate

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateFormatExample {
    public static void main(String[] args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");

        LocalDate localDate = LocalDate.of(2020, 1, 31);

        System.out.println(localDate.format(dateTimeFormatter));

    }
}
# Output
31/01/2020

使用 DateTimeFormatter 格式化 LocalDateTime

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

public class LocalDateTimeFormatExample {
    public static void main(String[] args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("E, MMM dd yyyy, hh:mm:ss a");

        LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 31, 10, 45, 30);

        System.out.println(localDateTime.format(dateTimeFormatter));

    }
}
# Output
Fri, Jan 31 2020, 10:45:30 AM

使用 DateTimeFormatter 格式化 ZonedDateTime

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

public class ZonedDateTimeFormatExample {
    public static void main(String[] args) {
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("E, MMM dd yyyy, hh:mm:ss a (VV)");

        ZonedDateTime zonedDateTime = ZonedDateTime.of(
                LocalDateTime.of(2020, 1, 31, 10, 30, 45),
                ZoneId.of("America/New_York"));
        
        System.out.println(zonedDateTime.format(dateTimeFormatter));

    }
}
# Output
Fri, Jan 31 2020, 10:30:45 AM (America/New_York)

使用 SimpleDateFormat 格式化日期和时间

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

public class DateFormatExample {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

        Date date = new Date();

        System.out.println(sdf.format(date));

    }
}
# Output
24/02/2020

让我们看另一个具有更复杂模式的示例:

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

public class DateFormatExample {
    public static void main(String[] args) {
        SimpleDateFormat sdf = new SimpleDateFormat("E, MMM dd yyyy, hh:mm:ss a");

        Calendar calendar = Calendar.getInstance();
        calendar.set(2020, 1, 26, 15, 30, 45);

        Date date = calendar.getTime();

        System.out.println(sdf.format(date));

    }
}
# Output
Wed, Feb 26 2020, 03:30:45 PM

相关文章