如何在Java中获取时区的当前日期和时间?

时间:2009-08-20 10:50:04

标签: java timezone jodatime

我的应用程序托管在伦敦服务器中。我在西班牙马德里。所以时区是-2小时。

如何使用我的时区获取当前日期/时间。

Date curr_date = new Date(System.currentTimeMillis());

e.g。

Date curr_date = new Date(System.currentTimeMillis("MAD_TIMEZONE"));

使用Joda-Time

DateTimeZone zone = DateTimeZone.forID("Europe/Madrid");
DateTime dt = new DateTime(zone);
int day = dt.getDayOfMonth();
int year = dt.getYear();
int month = dt.getMonthOfYear();
int hours = dt.getHourOfDay();
int minutes = dt.getMinuteOfHour();

13 个答案:

答案 0 :(得分:84)

Date 始终基于UTC ...或时区中立,具体取决于您希望如何查看它。仅Date 表示某个时间点;它独立于时区,自Unix时代以来只有几毫秒。没有“Date的本地实例”的概念。将DateCalendar和/或TimeZone.getDefault()结合使用可以使用“本地”时区。使用TimeZone.getTimeZone("Europe/Madrid")获取马德里时区。

...或使用Joda Time,这往往会让整个事情变得更加清晰,IMO。在Joda Time中,您将使用DateTime值,该值是特定日历系统和时区中的即时时间

在Java 8中,你使用的是java.time.ZonedDateTime,它是Joda Time的DateTime的Java 8等价物。

答案 1 :(得分:49)

正如Jon Skeet所说,java.util.Date没有时区。 Date对象表示自1970年1月1日上午12:00(UTC)以来的毫秒数。它不包含时区信息。

将Date对象格式化为字符串时,例如使用SimpleDateFormat,然后可以在DateFormat对象上设置时区,让它知道您要在哪个时区显示日期和时间:

Date date = new Date();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

// Use Madrid's time zone to format the date in
df.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

System.out.println("Date and time in Madrid: " + df.format(date));

如果您想要运行程序的计算机的本地时区,请使用:

df.setTimeZone(TimeZone.getDefault());

答案 2 :(得分:16)

使用Calendar很简单:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Madrid"));
Date currentDate = calendar.getTime();

答案 3 :(得分:7)

使用Java 8及更高版本内置的 java.time 类:

public static void main(String[] args) {
        LocalDateTime localNow = LocalDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(localNow);
        // Prints current time of given zone without zone information : 2016-04-28T15:41:17.611
        ZonedDateTime zoneNow = ZonedDateTime.now(TimeZone.getTimeZone("Europe/Madrid").toZoneId());
        System.out.println(zoneNow);
        // Prints current time of given zone with zone information : 2016-04-28T15:41:17.627+02:00[Europe/Madrid]
    }

答案 4 :(得分:3)

检查这可能会有所帮助。对我来说很好。代码还涵盖了夏令时

    TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
    Calendar cal = Calendar.getInstance();      
    // If needed in hours rather than milliseconds
    int LocalOffSethrs = (int) ((cal.getTimeZone().getRawOffset()) *(2.77777778 /10000000));        
    int ChinaOffSethrs = (int) ((tz.getRawOffset()) *(2.77777778 /10000000));       
    int dts = cal.getTimeZone().getDSTSavings();
    System.out.println("Local Time Zone : " + cal.getTimeZone().getDisplayName());
    System.out.println("Local Day Light Time Saving : " + dts);
    System.out.println("China Time : " + tz.getRawOffset());
    System.out.println("Local Offset Time from GMT: " + LocalOffSethrs);
    System.out.println("China Offset Time from GMT: " + ChinaOffSethrs);    
    // Adjust to GMT
    cal.add(Calendar.MILLISECOND,-(cal.getTimeZone().getRawOffset()));  
    // Adjust to Daylight Savings
    cal.add(Calendar.MILLISECOND, - cal.getTimeZone().getDSTSavings());
    // Adjust to Offset
    cal.add(Calendar.MILLISECOND, tz.getRawOffset());       
    Date dt = new Date(cal.getTimeInMillis());              
    System.out.println("After adjusting offset Acctual China Time :" + dt); 

答案 5 :(得分:2)

您可以使用JodaTime。关于TimeZone,Java.util.Date非常有限。

答案 6 :(得分:1)

我无法使用日历工作。你必须使用DateFormat

//Wednesday, July 20, 2011 3:54:44 PM PDT
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());

//Wednesday, July 20, 2011
df = DateFormat.getDateInstance(DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateString = df.format(new Date());

//3:54:44 PM PDT
df = DateFormat.getTimeInstance(DateFormat.FULL);
df.setTimeZone(Timezone.getTimeZone("PST"));
final String timeString = df.format(new Date());

答案 7 :(得分:0)

以下是一个例子:

Calendar c = Calendar.getInstance(TimeZone.getDefault());
Date date = c.getTime();

答案 8 :(得分:0)

以下是为您的区域寻找时间的一些步骤:

现在日期=新日期();

 DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");  
 df.setTimeZone(TimeZone.getTimeZone("Europe/London"));  

 System.out.println("timeZone.......-->>>>>>"+df.format(now));  

答案 9 :(得分:0)

24小时格式的日期

输出:2020年2月14日19:56:49 PM

 Date date = new Date();
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));

12小时格式的日期

输出:2020年2月14日晚上7:57:11

 Date date = new Date();`enter code here`
 DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss aa");
 dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London"));
 System.out.println("date is: "+dateFormat.format(date));

答案 10 :(得分:0)

获取您所在区域的日期和时间。

Date date = new Date();
DateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
df.setTimeZone(TimeZone.getDefault());
df.format(date);

答案 11 :(得分:0)

java.time

java.util 日期时间 API 及其格式化 API SimpleDateFormat 已过时且容易出错。建议完全停止使用它们并切换到 modern Date-Time API*

另外,下面引用的是来自 home page of Joda-Time 的通知:

<块引用>

请注意,从 Java SE 8 开始,要求用户迁移到 java.time (JSR-310) - JDK 的核心部分,取代了该项目。

使用 java.time(现代日期时间 API)的解决方案:如果您只想获取日期和时间(而不是时区信息),您可以使用 LocalDateTime.#now(ZoneId) .

非参数化重载,LocalDateTime.#now 使用 JVM 的时区返回当前日期时间。相当于使用 LocalDateTime.now(ZoneId.systemDefault())

演示:

import java.time.LocalDateTime;
import java.time.ZoneId;

public class Main {
    public static void main(String[] args) {
        LocalDateTime now = LocalDateTime.now(ZoneId.of("Europe/Madrid"));
        System.out.println(now);
    }
}

样本运行的输出:

2021-07-25T15:54:31.574424

ONLINE DEMO

如果要获取日期和时间以及时区信息,可以使用 ZonedDateTime.#now(ZoneId)。它的非参数化变体的行为方式与上述相同。

演示:

import java.time.ZoneId;
import java.time.ZonedDateTime;

public class Main {
    public static void main(String[] args) {
        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Europe/Madrid"));
        System.out.println(now);
    }
}

样本运行的输出:

2021-07-25T16:08:54.741773+02:00[Europe/Madrid]

ONLINE DEMO

Trail: Date Time 了解有关现代 Date-Time API 的更多信息。


* 出于任何原因,如果您必须坚持使用 Java 6 或 Java 7,您可以使用 ThreeTen-Backport,它将大部分 java.time 功能向后移植到 Java 6 & 7. 如果您正在为 Android 项目工作并且您的 Android API 级别仍然不符合 Java-8,请检查 Java 8+ APIs available through desugaringHow to use ThreeTenABP in Android Project

答案 12 :(得分:-2)

DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());