Java 格式化日历

Java 格式化日历,java,calendar,Java,Calendar,我需要格式化日历,只获取日期DD/MM/YY,但不转换为字符串,我需要将其转换为日期数据类型 SimpleDateFormat simpleDate = new SimpleDateFormat("dd/M/yy"); Calendar cal2 = new GregorianCalendar(simpleDate); dateFormat.format(date); //Here i need to store the Date (dd/M/yy) into a Date kin of va

我需要格式化日历,只获取日期DD/MM/YY,但不转换为字符串,我需要将其转换为日期数据类型

SimpleDateFormat simpleDate = new SimpleDateFormat("dd/M/yy");
Calendar cal2 = new GregorianCalendar(simpleDate);
 dateFormat.format(date); //Here i need to store the Date (dd/M/yy) into a Date kin of variable. (NO STRING)

因此,当我需要更新日历时,日期结果将反映更改。

我不知道这是否足够接近,如果有经验的人可以检查一下,那就太好了

将组合的“日期和时间”
java.util.date
截断为仅包含日期组件,将其有效地保留在午夜

public static Date truncateTime (Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime( date);
cal.set( Calendar.HOUR_OF_DAY, 0);
cal.set( Calendar.MINUTE, 0);
cal.set( Calendar.SECOND, 0);
cal.set( Calendar.MILLISECOND, 0);
return cal.getTime();
}

没有格式化日期之类的东西 日期时间类中存储的日期时间值没有格式

日期时间对象可以生成一个字符串对象,其文本采用某种格式来表示日期时间的值。但是字符串和日期时间是分开的,彼此不同

java.time 该类表示一个仅限日期的值,不含一天中的时间和时区

时区对于确定
LocalDate
至关重要。对于任何给定的时刻,全球各地的日期都因时区而异。例如,在蒙特勒尔,午夜过后几分钟仍然是“昨天”

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
避免使用麻烦的旧日期时间类,如java.util.date和java.util.Calendar。仅使用java.time类

gregorianalendar
如果您有一个
GregorianCalendar
对象,请通过调用添加到旧类中的新方法,将其转换为
ZoneDateTime

从那里得到一个
LocalDate
。ZoneDateTime对象自己指定的时区用于确定该日期

LocalDate localDate = zdt.toLocalDate();
java.util.Date转换
如果您有一个
java.util.Date
对象,请将其转换为
Instant
。此类表示UTC时间线上的一个时刻

Instant instant = myUtilDate.toInstant();
应用时区以获取
ZoneDateTime
。然后获取一个
LocalDate
,如上面所示

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );
LocalDate localDate = zdt.toLocalDate();
不变对象 time类遵循设计。新的java.time对象不是改变(mutate)java.time对象的值或属性,而是基于原始对象的属性实例化

生成字符串 如果要生成表示
LocalDate
值的字符串,请定义格式模式

DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/M/yy" );
String output = localDate.format( formatter );

顺便说一下,我强烈建议不要使用两位数的年份。产生的歧义和与解析相关的问题不值得节省两个字符。

阅读本文,理解其答案,然后你就会知道如何为你的
日历
子类实现同样的效果。亲爱的Down投票者:请在投票时留下批评意见。提问者要求的只是日期格式,你发布的是一个完整的大教堂。。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/M/yy" );
String output = localDate.format( formatter );