問題描述
我有方法根據(jù)時(shí)區(qū)查找月末日期.
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
.
但是,它應(yīng)該給我 CET 的輸出.
It should, however, give me an output in CET.
我錯(cuò)過了什么?
推薦答案
Calendar.getTime()
方法返回一個(gè) Date 對(duì)象,然后將其打印在代碼中.問題是 Date
類 不包含任何時(shí)區(qū)的概念,即使您使用 Calendar.getInstance()
指定了時(shí)區(qū)稱呼.是的,這確實(shí)令人困惑.
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.
因此,為了在特定時(shí)區(qū)打印 Date
對(duì)象,您必須使用 SimpleDateFormat 類,打印前必須調(diào)用 SimpleDateFormat.setTimeZone()
指定時(shí)區(qū).
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.
這是一個(gè)例子:
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
這篇關(guān)于Java:根據(jù)時(shí)區(qū)計(jì)算月末日期的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!