如何将时间戳转换为日期或日期时间对象?

发布于 2024-12-05 21:19:16 字数 522 浏览 0 评论 0原文

我正在使用 ResultSet.getTimestamp() 从数据库中检索时间戳对象,但我想要一种简单的方法来获取 MM/DD/YYYY 格式的日期code> 和格式为 HH:MM xx 的时间。我正在修补,看来我可以通过使用 Java 中的 Date 和/或 DateTime 对象来做到这一点。这是最好的方法,还是我什至需要转换时间戳来完成此任务?任何建议都会有帮助。

....
while(resultSet.next()) {
    Timestamp dtStart = resultSet.getTimestamp("dtStart");
    Timestamp dtEnd = resultSet.getTimestamp("dtEnd");

    // I would like to then have the date and time
    // converted into the formats mentioned...
    ....
}
....

I'm retrieving a timestamp object from a database using ResultSet.getTimestamp(), but I'd like an easy way to get the date in the format of MM/DD/YYYY and the time in a format of HH:MM xx. I was tinkering around, it it looks as though I can do such by making use of the Date and/or DateTime objects within Java. Is that the best way to go, or do I even need to convert the timestamp to accomplish this? Any recommendations would be helpful.

....
while(resultSet.next()) {
    Timestamp dtStart = resultSet.getTimestamp("dtStart");
    Timestamp dtEnd = resultSet.getTimestamp("dtEnd");

    // I would like to then have the date and time
    // converted into the formats mentioned...
    ....
}
....

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

对你的占有欲 2024-12-12 21:19:16
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");

        System.out.println(simpleDateFormat.format(timestamp));
        System.out.println(simpleDateFormat.format(date));
    }
}
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {

    public static void main(String[] args) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        Date date = new Date(timestamp.getTime());

        // S is the millisecond
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy' 'HH:mm:ss:S");

        System.out.println(simpleDateFormat.format(timestamp));
        System.out.println(simpleDateFormat.format(date));
    }
}
从此见与不见 2024-12-12 21:19:16

java.sql.Timestamp< /a> 是 java.util 的子类.日期。所以,只是向上倾斜它。

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

使用 SimpleDateFormat并创建 Joda DateTime 应该很简单。

java.sql.Timestamp is a subclass of java.util.Date. So, just upcast it.

Date dtStart = resultSet.getTimestamp("dtStart");
Date dtEnd = resultSet.getTimestamp("dtEnd");

Using SimpleDateFormat and creating Joda DateTime should be straightforward from this point on.

御弟哥哥 2024-12-12 21:19:16

java.time

现代答案:使用 java.time(现代 Java 日期和时间 API)来进行日期和时间工作。早在 2011 年,使用 Timestamp 类是正确的,但从 JDBC 4.2 开始,不再建议这样做。

为了您的工作,我们需要一个时区和几个格式化程序。我们也可以将它们声明为静态:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

现在代码可以是:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

示例输出(使用提出问题的时间):

日期:2011年9月20日;时间:18:13-0400

在您的数据库中,建议使用timestamp with time zone作为时间戳。如果这就是您所得到的,请像我在代码中所做的那样检索 OffsetDateTime 。在分别格式化日期和时间之前,我还将检索到的值转换为用户的时区。我以 America/Marigot 提供的时区为例,请提供您自己的时区。当然,如果您不需要,也可以省略时区转换。

如果 SQL 中的数据类型只是一个没有时区的timestamp,请改为检索 LocalDateTime。例如:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

无论细节如何,我相信您也会对 dtEnd 执行类似的操作。

我不确定 HH:MM xx 中的 xx 是什么意思。我只是将其保留在格式模式字符串中,该字符串会生成不带冒号的以小时和分钟为单位的 UTC 偏移量。

链接: Oracle 教程:日期时间 解释如何使用java.time。

java.time

Modern answer: use java.time, the modern Java date and time API, for your date and time work. Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.

For your work we need a time zone and a couple of formatters. We may as well declare them static:

static ZoneId zone = ZoneId.of("America/Marigot");
static DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("MM/dd/uuuu");
static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("HH:mm xx");

Now the code could be for example:

    while(resultSet.next()) {
        ZonedDateTime dtStart = resultSet.getObject("dtStart", OffsetDateTime.class)
                 .atZoneSameInstant(zone);

        // I would like to then have the date and time
        // converted into the formats mentioned...
        String dateFormatted = dtStart.format(dateFormatter);
        String timeFormatted = dtStart.format(timeFormatter);
        System.out.format("Date: %s; time: %s%n", dateFormatted, timeFormatted);
    }

Example output (using the time your question was asked):

Date: 09/20/2011; time: 18:13 -0400

In your database timestamp with time zone is recommended for timestamps. If this is what you’ve got, retrieve an OffsetDateTime as I am doing in the code. I am also converting the retrieved value to the user’s time zone before formatting date and time separately. As time zone I supplied America/Marigot as an example, please supply your own. You may also leave out the time zone conversion if you don’t want any, of course.

If the datatype in SQL is a mere timestamp without time zone, retrieve a LocalDateTime instead. For example:

        ZonedDateTime dtStart = resultSet.getObject("dtStart", LocalDateTime.class)
                 .atZone(zone);

No matter the details I trust you to do similarly for dtEnd.

I wasn’t sure what you meant by the xx in HH:MM xx. I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.

Link: Oracle tutorial: Date Time explaining how to use java.time.

清风挽心 2024-12-12 21:19:16

您还可以从时间戳获取 DateTime 对象,包括您当前的夏令时:

public DateTime getDateTimeFromTimestamp(Long value) {
    TimeZone timeZone = TimeZone.getDefault();
    long offset = timeZone.getOffset(value);
    if (offset < 0) {
        value -= offset;
    } else {
        value += offset;
    }
    return new DateTime(value);
}    

You can also get DateTime object from timestamp, including your current daylight saving time:

public DateTime getDateTimeFromTimestamp(Long value) {
    TimeZone timeZone = TimeZone.getDefault();
    long offset = timeZone.getOffset(value);
    if (offset < 0) {
        value -= offset;
    } else {
        value += offset;
    }
    return new DateTime(value);
}    
猥琐帝 2024-12-12 21:19:16

LocalDateTime dtStart = rs.getTimestamp("dtStart").toLocalDateTime();

将此 Timestamp 对象转换为代码 LocalDateTime。
该转换创建一个代表 LocalDateTime 的代码
同年、同月、同月日、时、分、秒和纳秒
日期时间值作为此代码本地时区的时间戳。

从1.8开始

LocalDateTime dtStart = rs.getTimestamp("dtStart").toLocalDateTime();

Converts this Timestamp object to a code LocalDateTime.
The conversion creates a code LocalDateTime that represents the
same year, month, day of month, hours, minutes, seconds and nanos
date-time value as this code Timestamp in the local time zone.

since 1.8

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文