【问题标题】:Java get date using only the utility packageJava 仅使用实用程序包获取日期
【发布时间】:2014-05-09 13:23:23
【问题描述】:

以下代码获取日期:

private static String get_date() {
    return (new SimpleDateFormat("yyyy/MM/dd HH:mm:ss")).format(Calendar.getInstance().getTime());
}

使用import java.text.SimpleDateFormat;

我怎样才能仅使用import java.util.*; 来完成上述操作

这样可以吗?为什么我会收到警告?

Date date= new java.util.Date();
        String s = (date.getYear()+1900)+"/"+date.getMonth()+"/"+date.getDay()+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();

【问题讨论】:

  • SimpleDateFormat的代码复制到你的代码中?
  • 您可以使用日历并使用“calendar.get(Calendar.HOUR) 等构建相同的字符串。
  • ... java.text 包有什么问题?毕竟这是一个 JRE 包..
  • 这是一个大学项目,我们只能使用 java.util.*

标签: java


【解决方案1】:

String.format() 是你的朋友。

public static String formatDate(Date date) {
    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    String template = "%04d/%02d/%02d %02d:%02d:%02d";
    return String.format(template, cal.get(Calendar.YEAR),
        cal.get(Calendar.MONTH) + 1, cal.get(Calendar.DAY_OF_MONTH),
        cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE),
        cal.get(Calendar.SECOND));
}

public static void main(String[] args) {
    System.out.println(formatDate(new Date()));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-15
    • 1970-01-01
    • 2016-11-13
    • 1970-01-01
    • 2023-03-11
    • 2020-07-16
    • 1970-01-01
    相关资源
    最近更新 更多