简体   繁体   English

如何将 LocalDate 格式化为字符串?

[英]How to format LocalDate to string?

我有一个名为 date 的 LocalDate 变量,当我打印它时显示 1988-05-05 我需要将其转换为打印为 05.May 1988.How to do this?

SimpleDateFormat will not work if he is starting with LocalDate which is new in Java 8. From what I can see, you will have to use DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html .如果他从 Java 8 中新增的 LocalDate 开始,SimpleDateFormat 将不起作用。据我所知,您将不得不使用 DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/时间/格式/DateTimeFormatter.html

LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);

That should print 05 May 1988. To get the period after the day and before the month, you might have to use "dd'.LLLL yyyy"那应该打印 05 May 1988。要获得一天之后和一个月之前的时间段,您可能必须使用“dd'.LLLL y​​yyy”

可以简写为:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));

上面的答案显示了今天

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

Ex. 防爆。 You can use any kind of date pattern 1. dd/MM/yyyy 2. dd/MM/yy 3. yyyy/MM/dd 您可以使用任何类型的日期模式1.dd / MM / yyyy 2.dd / MM / yy 3.yyyy / MM / dd

java.time时间

Unfortunately, all existing answers have missed a crucial thing, Locale .不幸的是,所有现有的答案都遗漏了一个关键的东西, Locale

A date-time parsing/formatting type (eg DateTimeFormatter of the modern API or SimpleDateFormat of the legacy API) is Locale -sensitive.日期时间解析/格式化类型(例如现代 API 的DateTimeFormatter或遗留 API 的SimpleDateFormat )是Locale敏感的。 The symbols used in its pattern print the text based on the Locale used with them.其模式中使用的符号根据与它们一起使用的Locale打印文本。 In absence of a Locale , it uses the default Locale of the JVM.在没有Locale的情况下,它使用 JVM 的默认Locale Check this answer to learn more about it.检查此答案以了解更多信息。

The text in the expected output, 05.May 1988 is in English and thus, the existing solutions will produce the expected result only as a result of mere coincidence (when the default Locale of the JVM an English Locale ).预期输出中的文本05.May 1988是英文的,因此,现有的解决方案将仅作为巧合的结果(当 JVM 的默认Locale为 English Locale )产生预期结果。

Solution using java.time , the modern date-time API * :使用java.time解决方案, 现代日期时间 API *

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

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(1988, 5, 5);
        final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd.MMMM uuuu", Locale.ENGLISH);
        String output = dtf.format(date);
        System.out.println(output);
    }
}

Output:输出:

05.May 1988

Here, you can use yyyy instead of uuuu but I prefer u to y .在这里,您可以使用yyyy而不是uuuu我更喜欢u而不是y

Learn more about the modern date-time API from Trail: Date Time .Trail: Date Time 中了解有关现代日期时间 API 的更多信息。


* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project . * 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和您的 Android API 工作级别仍然不符合 Java-8,请检查 通过 desugaringHow to use ThreeTenABP in Android Project 可用的 Java 8+ APIs

With the help of ProgrammersBlock posts I came up with this.在 ProgrammersBlock 帖子的帮助下,我想出了这个。 My needs were slightly different.我的需求略有不同。 I needed to take a string and return it as a LocalDate object.我需要获取一个字符串并将其作为 LocalDate 对象返回。 I was handed code that was using the older Calendar and SimpleDateFormat.我收到了使用旧日历和 SimpleDateFormat 的代码。 I wanted to make it a little more current.我想让它更流行一点。 This is what I came up with.这就是我想出的。

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


    void ExampleFormatDate() {

    LocalDate formattedDate = null;  //Declare LocalDate variable to receive the formatted date.
    DateTimeFormatter dateTimeFormatter;  //Declare date formatter
    String rawDate = "2000-01-01";  //Test string that holds a date to format and parse.

    dateTimeFormatter = DateTimeFormatter.ISO_LOCAL_DATE;

    //formattedDate.parse(String string) wraps the String.format(String string, DateTimeFormatter format) method.
    //First, the rawDate string is formatted according to DateTimeFormatter.  Second, that formatted string is parsed into
    //the LocalDate formattedDate object.
    formattedDate = formattedDate.parse(String.format(rawDate, dateTimeFormatter));

}

Hopefully this will help someone, if anyone sees a better way of doing this task please add your input.希望这会对某人有所帮助,如果有人看到执行此任务的更好方法,请添加您的意见。

There is a built-in way to format LocalDate in Joda libraryJoda 库中有一种内置的格式化 LocalDate 的方法

import org.joda.time.LocalDate;

LocalDate localDate = LocalDate.now();
String dateFormat = "MM/dd/yyyy";
localDate.toString(dateFormat);

In case you don't have it already - add this to the build.gradle:如果您还没有 - 将其添加到 build.gradle:

implementation 'joda-time:joda-time:2.9.5'

Happy coding!快乐编码! :) :)

A pretty nice way to do this is to use SimpleDateFormat I'll show you how:一个很好的方法是使用SimpleDateFormat我将向您展示如何:

SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);

I see that you have the date in a variable:我看到你在一个变量中有日期:

sdf.format(variable_name);

Cheers.干杯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM