【问题标题】:Separate Date and Time objects单独的日期和时间对象
【发布时间】:2013-02-27 17:04:36
【问题描述】:

我有一个网络表单,用户可以在其中从日历弹出窗口中选择日期,从下拉列表中选择时间。目前我正在尝试使用 Date 对象存储日期。

@Required
public Date date;

这个对象的输出是这样的:

格林威治标准时间 1970 年 1 月 1 日 00:00:00

我真正想做的是将它分开并将日期以 27/02/2013 之类的格式存储,并将时间作为 24 小时格式的单独对象,例如23:45。我不确定如何用 java 做到这一点。

使用 SimpleDateFormat 解决:

//also the import
import java.text.*;

@Required
public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy");
public String date = simpleDateFormat.format(new Date());

@Required
public SimpleDateFormat simpleTimeFormat = new SimpleDateFormat("hh:mm");
public String time = simpleTimeFormat.format(new Date());

【问题讨论】:

    标签: java date time


    【解决方案1】:

    看看Calendar 类。它具有获取不同“日期部分”所需的所有方法。另外,请查看 java 中的 SimpleDateFormat 类以按照需要的方式格式化日期。

    日历 - http://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html

    SimpleDateFormat - http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

    【讨论】:

    • 感谢您,我使用了 SimpleDateFormat 并更新了答案以包含我的解决方案。
    【解决方案2】:

    试试这个:

    SimpleDateFormat dateFormatter = new SimpleDateFormat("dd/MM/yyyy");
    SimpleDateFormat timeFormatter = new SimpleDateFormat("HH:mm:ss");
    
    String dateAsString = dateFormatter.format(date);
    String timeAsString = timeFormatter.format(date);
    

    【讨论】:

      猜你喜欢
      • 2015-03-22
      • 1970-01-01
      • 1970-01-01
      • 2018-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-10
      • 1970-01-01
      相关资源
      最近更新 更多