java中将日历日期转换为yyyy-MM-dd格式 [英] Calendar date to yyyy-MM-dd format in java

查看:55
本文介绍了java中将日历日期转换为yyyy-MM-dd格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将日历日期转换为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.

当你使用像 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.

这篇关于java中将日历日期转换为yyyy-MM-dd格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆