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.
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.
Here's an example:
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()));
}
}
Here is the output on my computer:
calendar.getTime(): Fri Aug 31 01:40:17 UTC 2018
sdf.format(): 2018-Aug-31 03:40:17 CEST
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…