簡體   English   中英

如何在 Java 中獲取時區的當前日期和時間?

[英]How to get the current date and time of your timezone in Java?

我的應用程序托管在倫敦服務器中。 我在西班牙馬德里。 所以時區是-2小時。

如何使用我的時區獲取當前日期/時間。

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

例如

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

喬達時間

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();

Date始終基於 UTC... 或時區中立,具體取決於您希望如何查看它。 一個Date代表一個時間點; 它與時區無關,自 Unix 紀元以來只有幾毫秒。 沒有“ Date本地實例”的概念。 DateCalendar和/或TimeZone.getDefault()結合使用以使用“本地”時區。 使用TimeZone.getTimeZone("Europe/Madrid")獲取馬德里時區。

...或使用Joda Time ,這往往會使整個事情更清晰,IMO。 在 Joda Time 中,您將使用DateTime值,它是特定日歷系統和時區中的一個瞬間。

在 Java 8 中,您將使用java.time.ZonedDateTime ,它是 Java 8 中 Joda Time 的DateTime等效項。

正如 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());

使用 日歷很簡單:

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

使用 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]
    }

為此,您將使用JodaTime Java.util.Date 在 TimeZone 方面非常有限。

檢查這可能會有所幫助。 對我來說很好用。 代碼還涵蓋了夏令時

    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); 

我無法使用日歷使其正常工作。 你必須使用 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());

這是一個例子:

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

獲取您所在區域的日期和時間。

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

時間

java.util Date-Time API 及其格式化 API SimpleDateFormat已過時且容易出錯。 建議完全停止使用它們並切換到現代 Date-Time API *

另外,下面引用的是來自Joda-Time主頁的通知:

請注意,從 Java SE 8 開始,要求用戶遷移到 java.time (JSR-310) - 替代該項目的 JDK 的核心部分。

使用現代日期時間 API java.time解決方案:如果您只想獲取日期和時間(而不是時區信息),您可以使用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

在線演示

如果要獲取日期和時間以及時區信息,可以使用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]

在線演示

Trail: Date Time 中了解有關現代日期時間 API 的更多信息。


* 出於任何原因,如果您必須堅持使用 Java 6 或 Java 7,您可以使用ThreeTen-Backport,它將大部分java.time功能向后移植到 Java 6 和 7。如果您正在為 Android 項目和您的 Android API 工作級別仍然不符合 Java-8,請檢查 通過 desugaringHow to use ThreeTenABP in Android Project 可用的 Java 8+ APIs

你可以試試ZonedDateTime.now() 您可以在包 java.time 中找到它

import java.time.ZonedDateTime;

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

}

輸出(我在印度加爾各答):

2021-09-17T14:46:14.341+02:00[Europe/Madrid]

獲取變量的日期。

public static  String  getCurrentDate(){
    final ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Asia/Kolkata"));
    String Temporal= DateTimeFormatter.ofPattern("yyyy-MM-dd").format(now);
    String today= LocalDate.now().format(DateTimeFormatter.ofPattern(Temporal));
    return today;
}

以下是為您的區域查找時間的一些步驟:

現在日期 = 新日期();

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

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

24 小時格式的日期

輸出:14/02/2020 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 小時格式的日期

輸出:14/02/2020 07:57:11 PM

 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));
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
df.setTimeZone(TimeZone.getTimeZone("PST"));
final String dateTimeString = df.format(new Date());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM