問題描述
我有方法根據時區查找月末日期.
I have method to find month end date based on the timezone.
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
calendar.set(
Calendar.DAY_OF_MONTH,
calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
);
System.out.println(calendar.getTime());`
它顯示輸出:Thu Aug 30 18:04:54 PDT 2018
.
但是,它應該給我 CET 的輸出.
It should, however, give me an output in CET.
我錯過了什么?
推薦答案
Calendar.getTime()
方法返回一個 Date 對象,然后將其打印在代碼中.問題是 Date
類 不包含任何時區的概念,即使您使用 Calendar.getInstance()
指定了時區稱呼.是的,這確實令人困惑.
The Calendar.getTime()
method returns a Date object, which you then printed in your code. The problem is that the Date
class does not contain any notion of a timezone even though you had specified a timezone with the Calendar.getInstance()
call. Yes, that is indeed confusing.
因此,為了在特定時區打印 Date
對象,您必須使用 SimpleDateFormat 類,打印前必須調用 SimpleDateFormat.setTimeZone()
指定時區.
Thus, in order to print a Date
object in a specific timezone, you have to use the SimpleDateFormat class, where you must call SimpleDateFormat.setTimeZone()
to specify the timezone before you print.
這是一個例子:
import java.util.Calendar;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
public class TimeZoneTest {
public static void main(String argv[]){
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("CET"));
calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
System.out.println("calendar.getTime(): " + calendar.getTime());
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss z");
sdf.setTimeZone(TimeZone.getTimeZone("CET"));
System.out.println("sdf.format(): " + sdf.format(calendar.getTime()));
}
}
這是我電腦上的輸出:
calendar.getTime(): Fri Aug 31 01:40:17 UTC 2018
sdf.format(): 2018-Aug-31 03:40:17 CEST
這篇關于Java:根據時區計算月末日期的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!