简体   繁体   English

如何将 Timestamp 转换为 Date 或 DateTime 对象?

[英]How can I convert a Timestamp into either Date or DateTime object?

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 .我正在使用ResultSet.getTimestamp()从数据库中检索时间戳对象,但我想要一种简单的方法来获取格式为MM/DD/YYYY的日期和格式为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.我正在修补,看起来我可以通过使用 Java 中的 Date 和/或 DateTime 对象来做到这一点。 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...
    ....
}
....
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));
    }
}

java.sql.Timestamp is a subclass of java.util.Date . java.sql.Timestampjava.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.从这一点开始,使用SimpleDateFormat和创建 Joda DateTime应该很简单。

You can also get DateTime object from timestamp, including your current daylight saving time:您还可以从时间戳获取 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);
}    

java.time时间

Modern answer: use java.time, the modern Java date and time API, for your date and time work.现代答案:使用 java.time,现代 Java 日期和时间 API,用于您的日期和时间工作。 Back in 2011 it was right to use the Timestamp class, but since JDBC 4.2 it is no longer advised.早在 2011 年,使用Timestamp类是正确的,但从 JDBC 4.2 开始,不再建议使用它。

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;日期:09/20/2011; time: 18:13 -0400时间:18:13 -0400

In your database timestamp with time zone is recommended for timestamps.在您的数据库中timestamp with time zone建议timestamp with time zone时间戳作为时间戳。 If this is what you've got, retrieve an OffsetDateTime as I am doing in the code.如果这是您所拥有的, OffsetDateTime像我在代码中所做的那样检索OffsetDateTime 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.作为时区,我以 America/Marigot 为例,请提供您自己的时区。 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.如果 SQL 中的数据类型只是没有时区的timestamp ,则取而代之的是检索LocalDateTime For example:例如:

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

No matter the details I trust you to do similarly for dtEnd .不管细节如何,我相信你会对dtEnd做类似的dtEnd

I wasn't sure what you meant by the xx in HH:MM xx .我不确定你所说的HH:MM xxxx是什么意思。 I just left it in the format pattern string, which yields the UTC offset in hours and minutes without colon.我只是把它留在格式模式字符串中,它以小时和分钟为单位产生 UTC 偏移量,没有冒号。

Link: Oracle tutorial: Date Time explaining how to use java.time.链接: Oracle 教程:解释如何使用 java.time 的日期时间

LocalDateTime dtStart = rs.getTimestamp("dtStart").toLocalDateTime();<\/code>

将此 Timestamp 对象转换为代码 LocalDateTime。转换会创建一个代码 LocalDateTime,它表示与本地时区中的此代码 Timestamp 相同的年、月、日、小时、分钟、秒和 nanos 日期时间值。

从 1.8 开始

"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何将java.util.Date对象转换为dateTime的标准表示形式的受限形式 - How can I convert a java.util.Date object to the restricted form of the canonical representation of dateTime 如何将Excel日期转换为Java的时间戳? - How can I convert an Excel date into a Timestamp for Java? 如何转换ArrayList <Object> 到ArrayList <String> 或ArrayList <Timestamp> ? - How can I convert ArrayList<Object> to ArrayList<String> or ArrayList<Timestamp>? 如何修改我的@SQLUpdate将Joda DateTime对象转换为h2可读的时间戳? - How do I modify my `@SQLUpdate` to convert a `Joda` `DateTime` object into an `h2`-readable timestamp? 如何将特定日期设置为 Joda Time DateTime 对象? - How can I set a specific date into a Joda Time DateTime object? 如何使用Hibernate注释将Java日期映射到mysql中的DATETIME(默认情况下为TIMESTAMP) - How can I map a Java date to DATETIME in mysql (by default its TIMESTAMP) with Hibernate annotations 如何将时间戳转换为日期 - How convert Timestamp to Date 如何将日期时间转换为日期? - How to convert DateTime to Date? 如何将日期时间转换为日期 - How to convert DateTime to Date 如何避免“flexjson.JSONSerializer”将Datetime对象转换为时间戳? 我想要字符串像yyyy / MM / dd hh:mm:ss - How to avoid “flexjson.JSONSerializer” convert Datetime Object to Timestamp? I want string like yyyy/MM/dd hh:mm:ss
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM