【问题标题】:How do I convert "HH:MM" format string to Timestamp in Java?如何在 Java 中将“HH:MM”格式字符串转换为时间戳?
【发布时间】:2017-03-20 10:50:27
【问题描述】:

我有一个字符串09:28.,我想将此字符串转换为Timestamp 对象。

下面是我的代码:

Object d = getMappedObjectValue(reportBeamDataMap, ReportBeamConstant.DAT_STOPDATE);
Date stopDate1 = (Date)d;
SimpleDateFormat printFormat = new SimpleDateFormat("hh:mm");
String timeString = printFormat.format(stopDate1);

现在我想在String 上方作为Timestamp(仅 HH:MM)。该怎么做?

【问题讨论】:

  • 为什么不将stopDate1 转换为TimeStamp 而不是timeString
  • 因为 stopDate1 也有日期和其他时间数据。我只想要 HH:MM。所以我先把它们串起来。但没关系,对象 d1 = getMappedObjectValue(reportBeamDataMap, ReportBeamConstant.DAT_STOPDATE);日期 stopDate12 = (日期)d1; SimpleDateFormat printFormat1 = new SimpleDateFormat("hh:mm");字符串 timeString1 = printFormat.format(stopDate1);时间戳 tm1 = new Timestamp(printFormat1.parse(timeString1).getTime());这工作得很好。谢谢

标签: java string date datetime timestamp


【解决方案1】:

如果您正在寻找今天 hh:mm 的时间戳,那么试试这个

static String todaysFtoTimestamp(String f){
    long todaystimestamp = ((System.currentTimeMillis() / 86400000 )  * 86400 );
    //System.out.println("today: " + todaystimestamp);
    long todaysftimestamp = Integer.parseInt(fToTimestamp(f)) + todaystimestamp;
    //System.out.println("todayF: " + todaysftimestamp);
    return todaysftimestamp+"";
}
static String fToTimestamp(String f){
    String[] fArray = f.split(":");
    String r = "null hehe";
    int hours = Integer.parseInt(fArray[0]);
    int minutes = Integer.parseInt(fArray[1]);
    r = String.valueOf((minutes + (hours * 60))*60);
    return r ;
}

【讨论】:

    【解决方案2】:

    您可以使用 LocalTime 来存储时间(来自字符串,反之亦然),如下所示:

    选项(1):使用 Java8

    这个可以使用Java8的LocalTime API,可以看here

    String timeString = printFormat.format(stopDate1);
    //Get your localTime object from timeString
    LocalTime localTime = LocalTime.parse(timeString);
    

    static LocalTime parse(CharSequence text) 获取一个实例 LocalTime 来自文本字符串,例如 10:15。

    选项(2):不使用 Java8

    需要用到jodatime库API,可以看here

    【讨论】:

      【解决方案3】:

      请使用 parse 方法获取 Date 对象,然后构造 Timestamp 对象。

       try {
          Timestamp timestamp = new Timestamp(printFormat.parse(timeString).getTime());
          } catch (ParseException e) {
              e.printStackTrace();
          }
      

      【讨论】:

        【解决方案4】:

        时间戳格式必须为 yyyy-mm-dd hh:mm:ss[.fffffffff]

        您可以直接将日期对象转换为时间戳

         Timestamp timestamp = new Timestamp(stopDate1.getTime());
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-08-31
          • 2018-08-15
          • 1970-01-01
          • 1970-01-01
          • 2023-03-22
          • 1970-01-01
          • 1970-01-01
          • 2018-07-20
          相关资源
          最近更新 更多