如何在控制台打印“今天是2014年5月22日,下午2点04分”?

时间:2014-05-22 10:34:45

标签: java date time

对于Java学习者来说,这个简单的问题很头疼。我非常确定一个简单的答案可以帮助初学者。

以下是要求:

  • 在控制台Today is May 22, 2014 and it is 2:04 pm
  • 打印
  • 日期和时间是本地系统显示的当前时间(当地时间)
  • 使用的日期/时间格式符合JVM区域设置,这意味着在法国我会打印Today is 22 mai 2014 and it is 14:04
  • 在提供标准API解决方案之后,外部库只能作为替代方案。
  • 使用Java 7或更低版​​本。

这似乎离" hello world"难度级别,我仍然对我在寻找答案时看到的复杂性感到困惑。


现在仅供参考,以下是有关我找到的建议的信息,这让我感到疯狂:

  • 请勿使用Date,使用Calendarhere
  • 使用DateSimpleDateFormathere
  • 请勿使用java.util. {CalendarDate},here
  • 对于日期部分,请使用Calendar并将时间成分设置为零,here
  • 仅使用System.currentTimeMillis()获取日期和时间here

编辑:迈克尔提供的解决方案:

Date now = new Date();
DateFormat dateFmt = DateFormat.getDateInstance(DateFormat.LONG);
DateFormat timeFmt = DateFormat.getTimeInstance (DateFormat.SHORT);
System.out.println("Today is "   + dateFmt.format(now) +
                   " and it is " + timeFmt.format(now));

6 个答案:

答案 0 :(得分:3)

java.time

旧的日期时间 API(java.util 日期时间类型及其格式 API,SimpleDateFormat)已经过时且容易出错。建议完全停止使用,改用java.timemodern date-time API*

使用现代日期时间 API 的解决方案:

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class Main {
    public static void main(String args[]) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("'Today is' dd MMM uuuu 'and it is' HH:mm", Locale.FRENCH);
        LocalDateTime ldt = LocalDateTime.now(ZoneId.of("Europe/Paris"));
        System.out.println(dtf.format(ldt));
    }
}

输出:

Today is 05 mai 2021 and it is 11:50

注意事项:

  1. 如果您的 JVM 已将 Locale.FRENCH 设置为语言环境,请将 Locale.getDefault() 替换为 Locale.FRENCH
  2. 如果您的 JVM 已将 ZoneId.of("Europe/Paris") 设置为时区,请将 ZoneId.systemDefault() 替换为 LocalDateTime.now() 或直接使用 Europe/Paris

对于日期和时间格式的本地化,您也可以这样做:

        DateTimeFormatter dtfDate = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
        DateTimeFormatter dtfTime = DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT);
        
        ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Europe/Paris"));
        System.out.format("Today is %s and it is %s%n",
                zdt.format(dtfDate), zdt.format(dtfTime));

具有默认语言环境 Locale.FRENCH 的示例输出:

<块引用>

今天是 2021 年 5 月 5 日,现在是 19:08

Locale.US 示例:

<块引用>

今天是 2021 年 5 月 5 日,晚上 7:11

后一个片段还有另一个不同之处,即使用 ZonedDateTime 而不是 LocalDateTime。在以下情况下将是有利的:

  1. 如果您想(现在或以后)以 FULL 格式提供输出,其中包括时区,因此需要 ZonedDateTime
  2. 如果您想在任何时候将日期时间对象用于打印以外的任何其他用途,最安全的是它知道自己的时区。这可以防止一系列潜在错误。

modern date-time API 中了解有关 Trail: Date Time* 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

答案 1 :(得分:2)

您肯定希望使用new Date()来获取当前时间。

由于您需要本地化格式,请使用java.text.DateFormat的{​​{3}}和getDateInstance()工厂方法来获取格式化程序对象。查看重载版本以获得对格式样式的更多控制。

这就是你所需要的一切。

答案 2 :(得分:2)

试试这个(使用默认的JVM语言环境):

DateFormat df = new SimpleDateFormat("'Today is 'MMM dd, yyyy' and it is 'HH:mm");
System.out.println(df.format(new Date()));

如果您需要不同的区域设置,可以强制执行以下操作:

DateFormat df = new SimpleDateFormat("'Today is 'MMM dd, yyyy' and it is 'HH:mm", new Locale("en"));
System.out.println(df.format(new Date()));

或者您可以更新JVM的语言环境以覆盖系统: how do I set the default locale for my JVM?

答案 3 :(得分:1)

试试此代码

  DateFormat df = new SimpleDateFormat("MMM dd, yyyy");
  DateFormat tf = new SimpleDateFormat("HHH:mm aa");
  Date date = new Date();
  System.out.println("Today is "+df.format(date)+" and it is "+tf.format(date));

df是日期格式,tf是时间字符串的格式。

答案 4 :(得分:0)

将英语单词与本地化的日期时间值混合似乎很奇怪。但是你走吧。

避免使用java.util.Date/Calendar

与Java捆绑在一起的java.util.Date和.Calendar类非常麻烦。避免他们。使用一个像样的日期时间库,例如Joda-Time或Java 8中的新java.time包。

时区

你的问题忽略了时区的关键问题。

约达时间

Joda-Time 2.3中的示例代码。

DateTimeZone timeZoneParis = DateTimeZone.forID( "Europe/Paris" );
DateTime nowParis = DateTime.now( timeZoneParis ); // Paris time, but Québécois style.
String datePortion = DateTimeFormat.forStyle( "M-" ).withLocale( Locale.CANADA_FRENCH ).print( nowParis );
String timePortion = DateTimeFormat.forStyle( "-S" ).withLocale( Locale.CANADA_FRENCH ).print( nowParis );
// Tweak the Style argument: 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be omitted by specifying a style character '-'.
System.out.println( "Today is " + datePortion + " and it is " + timePortion );

答案 5 :(得分:-1)

继续使用Date和SimpleFormat。要以您需要的格式获取内容,您始终可以在日期字符串上调用String.split(X)来获取所需的不同部分。一旦你有这些作品,打印你需要的信息应该相对简单