我有一个LocalDate
名为 的变量date
,当我打印它时显示 1988-05-05 我需要将其转换为 05.May 1988 打印。如何做到这一点?
7 回答
如果他从 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);
那应该打印 1988 年 5 月 5 日。要获得一天之后和一个月之前的时间段,您可能必须使用“dd'.LLLL yyyy”
可以简称为:
LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));
java.time
不幸的是,所有现有的答案都错过了一个关键的事情,Locale
.
日期时间解析/格式化类型(例如DateTimeFormatter
现代 API 或SimpleDateFormat
遗留 API)是 -Locale
敏感的。其模式中使用的符号根据Locale
与它们一起使用的方式打印文本。在没有 aLocale
的情况下,它使用 JVM 的默认值Locale
。检查此答案以了解更多信息。
预期输出中的文本05.May 1988
是英文的,因此,现有解决方案将仅作为巧合的结果产生预期结果(当Locale
JVM 的默认值为 English时Locale
)。
使用现代日期时间 API *java.time
的解决方案:
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);
}
}
输出:
05.May 1988
在这里,您可以使用yyyy
代替,uuuu
但我更喜欢 u
使用y
.
从Trail: Date Time了解有关现代日期时间 API 的更多信息。
* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,则可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目和 Android API 工作level 仍然不符合 Java-8,请检查Java 8+ APIs available through desugaring和How to use ThreeTenABP in Android Project。
System.out.println(LocalDate.now().format(DateTimeFormatter.ofPattern("dd.MMMM yyyy")));
上面的答案显示了今天
在 ProgrammersBlock 帖子的帮助下,我想出了这个。我的需求略有不同。我需要获取一个字符串并将其作为 LocalDate 对象返回。我收到了使用旧日历和 SimpleDateFormat 的代码。我想让它更流行一点。这就是我想出的。
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));
}
希望这会对某人有所帮助,如果有人看到执行此任务的更好方法,请添加您的输入。
在Joda 库中有一种内置方法来格式化 LocalDate
import org.joda.time.LocalDate;
LocalDate localDate = LocalDate.now();
String dateFormat = "MM/dd/yyyy";
localDate.toString(dateFormat);
如果您还没有 - 将其添加到 build.gradle:
implementation 'joda-time:joda-time:2.9.5'
快乐编码!:)
一个很好的方法是使用SimpleDateFormat
I'll show you how:
SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);
我看到您在变量中有日期:
sdf.format(variable_name);
干杯。