java中的日历日期为yyyy-MM-dd格式

2022-01-11 00:00:00 date calendar converter java

如何将日历日期转换为yyyy-MM-dd格式.

How to convert calendar date to yyyy-MM-dd format.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
Date date = cal.getTime();             
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
String date1 = format1.format(date);            
Date inActiveDate = null;
try {
    inActiveDate = format1.parse(date1);
} catch (ParseException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

这将产生 inActiveDate = Wed Sep 26 00:00:00 IST 2012.但我需要的是2012-09-26.我的目的是使用 Hibernate 标准将此日期与我的数据库中的另一个日期进行比较.所以我需要 yyyy-MM-dd 格式的日期对象.

This will produce inActiveDate = Wed Sep 26 00:00:00 IST 2012. But what I need is 2012-09-26. My purpose is to compare this date with another date in my database using Hibernate criteria. So I need the date object in yyyy-MM-dd format.

推荐答案

Java Date 是自 1970 年 1 月 1 日 00:00:00 GMT 以来的毫秒数的容器.

A Java Date is a container for the number of milliseconds since January 1, 1970, 00:00:00 GMT.

p>

当你使用 System.out.println(date) 之类的东西时,Java 使用 Date.toString() 来打印内容.

When you use something like System.out.println(date), Java uses Date.toString() to print the contents.

更改它的唯一方法是覆盖 Date 并提供您自己的 Date.toString() 实现.现在在你启动你的 IDE 并尝试这个之前,我不会;它只会使事情复杂化.您最好将日期格式化为您想要使用(或显示)的格式.

The only way to change it is to override Date and provide your own implementation of Date.toString(). Now before you fire up your IDE and try this, I wouldn't; it will only complicate matters. You are better off formatting the date to the format you want to use (or display).

LocalDateTime ldt = LocalDateTime.now().plusDays(1);
DateTimeFormatter formmat1 = DateTimeFormatter.ofPattern("yyyy-MM-dd", Locale.ENGLISH);
System.out.println(ldt);
// Output "2018-05-12T17:21:53.658"

String formatter = formmat1.format(ldt);
System.out.println(formatter);
// 2018-05-12

Java 8 之前的版本

您应该使用 ThreeTen Backport

出于历史目的保留以下内容(作为原始答案)

The following is maintained for historical purposes (as the original answer)

你可以做的是格式化日期.

What you can do, is format the date.

Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, 1);
SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(cal.getTime());
// Output "Wed Sep 26 14:23:28 EST 2012"

String formatted = format1.format(cal.getTime());
System.out.println(formatted);
// Output "2012-09-26"

System.out.println(format1.parse(formatted));
// Output "Wed Sep 26 00:00:00 EST 2012"

这些实际上是相同的日期,表示方式不同.

These are actually the same date, represented differently.

相关文章