【问题标题】:How to get only the year from the Date Class如何从日期类中仅获取年份
【发布时间】:2014-08-31 12:20:51
【问题描述】:

有没有办法只从Date 类中获取年份并将其解析为字符串? 这是我使用的代码:

Date d1 = new Date();
d1.getYear();  `

以及如何将日期设置为DatTime.Now

就像在 C# 中一样?

【问题讨论】:

标签: android string date


【解决方案1】:

使用SimpleDateFormat

SimpleDateFormat sdf  = new SimpleDateFormat("yyyy");
System.out.println(sdf.format(new Date()));

输出:

2014

【讨论】:

  • 以及如何将日期变量设置为当前日期?
【解决方案2】:
public static String getCurrentDate(String format) {
    SimpleDateFormat sdfFrom = new SimpleDateFormat(format);
    Calendar currentTime = Calendar.getInstance();
    return (sdfFrom.format(currentTime.getTime()));
}

public static Date getCurrentDate() {
    Calendar currentTime = Calendar.getInstance();
    return currentTime.getTime();
}

try to use java 8 date 

【讨论】:

    猜你喜欢
    • 2017-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-16
    • 2018-04-29
    • 2020-06-02
    • 2018-10-05
    相关资源
    最近更新 更多