gpt4 book ai didi

java - 如何将 mili 秒格式更改为 yyyy-mm-dd hh :mm:ss to insert to mysql with datetype colunm

转载 作者:行者123 更新时间:2023-11-28 23:44:20 26 4
gpt4 key购买 nike

我想在 Wordpress 的 post_date 列中插入日期和时间。列数据类型为 datetime yyyy-mm-dd hh:mm:ss。我要生成的第一行是:2015-01-01 01:01:01 并在下一行 2015-01-01 01:02:01 添加 60 秒。

我找到了这段代码,但我不知道如何将毫秒格式转换为秒格式。它是 print 2015-11-22 15:41:29.496,但如何去掉“.496”?当我插入到 MySQL 时,我的数据类型是否被格式化为:datetime? wordpress 会理解吗?

import java.util.*;
import java.sql.*;

long retryDate = System.currentTimeMillis();

int sec = 60;

Timestamp original = new Timestamp(retryDate);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(original.getTime());
cal.add(Calendar.SECOND, sec);
Timestamp later = new Timestamp(cal.getTime().getTime());

System.out.println(original);
System.out.println(later);

最佳答案

使用 cal.set(Calendar.MILLISECOND, 0) 清除毫秒数。
使用 new Timestamp(cal.getTimeInMillis()) 获取 Timestamp

final int sec = 60;

Calendar cal = Calendar.getInstance();
cal.set(Calendar.MILLISECOND, 0);
Timestamp original = new Timestamp(cal.getTimeInMillis());

cal.add(Calendar.SECOND, sec);
Timestamp later = new Timestamp(cal.getTimeInMillis());

System.out.println(original);
System.out.println(later);

Java 8 版本使用 Instant :

final int sec = 60;

Instant instant = Instant.now().truncatedTo(ChronoUnit.SECONDS);
Timestamp original = Timestamp.from(instant);

instant = instant.plusSeconds(sec);
Timestamp later = Timestamp.from(instant);

System.out.println(original);
System.out.println(later);

关于java - 如何将 mili 秒格式更改为 yyyy-mm-dd hh :mm:ss to insert to mysql with datetype colunm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33853179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com