简体   繁体   English

设置日期对象 Java

[英]Set a Date Object Java

I have a date object myDate(say).我有一个日期对象 myDate(say)。 After doing the following:执行以下操作后:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.MONTH, 9);
cal.set(Calendar.DATE, 24);
cal.set(Calendar.YEAR, 2013);
cal.set(Calendar.HOUR,13);
cal.set(Calendar.MINUTE,45);
cal.set(Calendar.SECOND,52);

I want to set the myDate object to the above values and hence show the below output.我想将 myDate 对象设置为上述值,从而显示以下输出。

Mon Sep 09 13:45:52 PST 2013

Please let me know how to do it.请让我知道该怎么做。

import java.util.*;

public class DateTest {
    public static void main(String[] args) {
        Date myDate;
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, 8);
        cal.set(Calendar.DATE, 24);
        cal.set(Calendar.YEAR, 2013);
        cal.set(Calendar.HOUR,13);
        cal.set(Calendar.MINUTE,45);
        cal.set(Calendar.SECOND,52);
        myDate = cal.getTime();
        System.out.println(myDate);
    }
}

The months attribute starts from January = zero .月份属性从 January = zero 开始 Why oh why did Sun do such a counter-intuitive thing, I don't know.为什么哦,为什么 Sun 会做这种违反直觉的事情,我不知道。

import java.util.*;

public class DateTest {
    public static void main(String[] args) {
        Date myDate;
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.MONTH, 8);
        cal.set(Calendar.DATE, 24);
        cal.set(Calendar.YEAR, 2013);
        cal.set(Calendar.HOUR,13);
        cal.set(Calendar.MINUTE,45);
        cal.set(Calendar.SECOND,52);
        myDate = cal.getTime();
        System.out.println(myDate);
    }
}

One other consideration, the output has a timezone in it - if you want the timezone of the Java installation, no probs.另一个考虑因素是,输出中有一个时区 - 如果您想要 Java 安装的时区,没有问题。 If you want PST and the Java timezone default is somewhere else , then use the following constructor:如果您想要 PST并且 Java 时区默认值在其他地方,则使用以下构造函数:

TimeZone timezone = TimeZone.getTimeZone("America/Los_Angeles");
Calendar cal = Calendar.getInstance(timezone);

你可以写:

myDate.setTime(cal.getTimeInMillis());

使用SimpleDateFormat

new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy").format(cal.getTime())

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM