有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

Java:将时间从今天转换为时间戳

我使用的是Java6,我有一个从当前日期开始的时间作为字符串,如:14:21:16,我需要将其转换为^{} object以存储在数据库中

然而,似乎没有什么好方法可以从中获取时间戳^{}非常接近,但需要日期。有没有一种好方法可以从这样的字符串生成Timestamp对象


共 (6) 个答案

  1. # 2 楼答案

    使用组织。阿帕奇。平民时间。日期:

    Date today = DateUtils.truncate(new Date(), Calendar.DAY_OF_MONTH);    
    DateFormat df = new SimpleDateFormat("HH:mm:ss");
    Date time = df.parse("14:21:16");
    Timestamp time = new Timestamp(today.getTime() + time.getTime());
    
  2. # 3 楼答案

    String str = "14:21:16";
    DateFormat formatter = new SimpleDateFormat("HH:mm:ss"); 
    Date date = formatter.parse(str); 
    Timestamp timestamp = new Timestamp(date.getTime());
    
  3. # 4 楼答案

    就我个人而言,我会使用Joda Time将时间解析为LocalTime,并将其添加到今天的LocalDate中以获得LocalDateTime,然后使用您感兴趣的时区将其转换为Instant。(或使用LocalTime.toDateTimeToday(DateTimeZone)。)

    然后使用Timestamp(long)构造函数创建一个时间戳

    还有很多其他方法(例如,如果您真的需要,可以使用SimpleDateFormat而不是使用Joda-Time进行解析…)但最终您可能需要Timestamp(long)构造函数。(在这里使用Joda Time的好处是,很明显每个阶段都代表着什么——你不会试图将“时间”视为“日期和时间”,反之亦然。)

  4. # 5 楼答案

    我能想到的使用标准API的最佳方法并没有那么漂亮:

        // Get today's date and time.
        Calendar c1 = Calendar.getInstance();
        c1.setTime(new Date()); 
    
        // Get the required time of day, copy year, month, day.
        Calendar c2 = Calendar.getInstance();
        c2.setTime(java.sql.Time.valueOf("14:21:16"));
        c2.set(Calendar.YEAR, c1.get(Calendar.YEAR));
        c2.set(Calendar.MONTH, c1.get(Calendar.MONTH));
        c2.set(Calendar.DAY_OF_MONTH, c1.get(Calendar.DAY_OF_MONTH));
    
        // Construct required java.sql.Timestamp object.
        Timestamp time = new Timestamp(c2.getTimeInMillis());
    
        Let's see what we've done.
        System.out.println(time);
    

    请注意,java。sql。时间valueOf根据需要接受格式为“HH:MM:SS”的字符串。其他格式需要使用SimpleDataFormat

  5. # 6 楼答案

    这个怎么样:

    final String str = "14:21:16";
    final Timestamp timestamp =
        Timestamp.valueOf(
            new SimpleDateFormat("yyyy-MM-dd ")
            .format(new Date()) // get the current date as String
            .concat(str)        // and append the time
        );
    System.out.println(timestamp);
    

    输出:

    2011-03-02 14:21:16.0