关于我上面的问题,我想根据时区(吉隆坡)获取当前日期时间。我可以知道该怎么做吗?
下面是我当前的代码:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnTime = findViewById(R.id.btnTime);
tvTime = findViewById(R.id.tvTime);
btnTime.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String time = "Current time - " + format.format(calendar.getTime());
tvTime.setText(time);
}
});
}
最佳答案
马来西亚遵守 GMT+8,您可以像这样设置 SimpleDateFormat
的 TimeZone
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
format.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
String time = "Current time - " + format.format(calendar.getTime());
或者,更好的是,切换到 ThreeTenABP java.time
的向后移植,例如
ZonedDateTime klDateTime = LocalDateTime.now().atZone(ZoneId.of("Asia/Kuala_Lumpur"));
String time = "Current time - " + klDateTime.format(DateTimeFormatter
.ofPattern("yyyy-MM-dd HH:mm:ss"));
关于java - 安卓/JAVA : Get current time based on timezone,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507896/