在java中表示日期的最佳方式

时间:2015-04-07 01:42:59

标签: java date

我正在设计一个预订系统,需要以2015年的格式表示日期,格式为" dd,mmm,2015" (例如" 05 jan 2015")。我对如何做到这一点有点困惑,看起来像Date支持这样的东西,但现在已经折旧了?格雷戈里日历(GregorianCalender)(2015年,01,05)是2015年日期或其他对象的完整表示,我对格里历日历类感到困惑吗?

4 个答案:

答案 0 :(得分:4)

java.time.LocalDate

如果您使用的是Java 8或更高版本,则应使用java.time.LocalDate类。

要解析和格式化该日期,您需要使用java.time.format.DateTimeFormatter类。

用法示例:

LocalDate date = LocalDate.of(2015, Month.JANUARY, 5);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd, MMM, yyyy", Locale.ENGLISH);
System.out.println(formatter.format(date)); // prints "05, Jan, 2015"
date = LocalDate.parse("06, Jan, 2015", formatter);
System.out.println(date.getDayOfMonth()); // prints "6"

如果您使用的是Java 7或更早版本,则应使用java.util.Date类表示日期,java.util.GregorianCalendar从字段中创建日期对象或检索日期组件,然后使用java.text.SimpleDateFormat解析和格式化。用法示例:

GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.set(2015, Calendar.JANUARY, 5);
Date date = gregorianCalendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd, MMM, yyyy", Locale.ENGLISH);
System.out.println(simpleDateFormat.format(date)); // prints "05, Jan, 2015"
date = simpleDateFormat.parse("06, Jan, 2015");
gregorianCalendar.setTime(date);
System.out.println(gregorianCalendar.get(Calendar.DAY_OF_MONTH)); // prints "6"

答案 1 :(得分:0)

我不确定您在哪里看到了弃用,但我仍然会使用Date和DateFormat对象。

DateFormat format = new SimpleDateFormat("dd MM");
String output;

output = format.format(new Date()) + " 2015";
System.out.println(output);

输出:

06 04 2015

如果要删除0,请将代码更改为:

    DateFormat format = new SimpleDateFormat("dd MM");
    String output;

    output = format.format(new Date());
    output = output.replaceAll("0", "") + " 2015";
    System.out.println(output);

输出:

6 4 2015

有关SimpleDateFormat的更多信息,请参阅javadoc:SimpleDateFormat Reference

答案 2 :(得分:0)

Java 8 Date and Time API为日期和时间使用提供了很多灵活性。 详细了解Java 8 Date and Time

答案 3 :(得分:0)

这将使您今天的日期为int,以及当年的月份。您可以使用此int来比较日期。即,dateInt_1 < dateInt_2意味着date1出现在date2之前。 dateInt_1 == dateInt_2意味着两个日期是相同的。等

int dateInt = Integer.parseInt(new SimpleDateFormat("yyyyMMdd").format(new Date()));