即使我从手机更改了当前时区并更改了时间,我也想根据当前时区获取当前时间,但是我仍然应该能够获取当前时间和日期。如何获得?
Time currentTime = new Time();
currentTime.setToNow();
Calendar cal = Calendar.getInstance();
TimeZone tz = cal.getTimeZone();
Date date = cal.getTime();
strDate = date.toString();
答案 0 :(得分:1)
使用此方法获取本地时间
public static Date getLocalDate(String timeStamp) {
int index = timeStamp.indexOf("+");
String dateTime;
if (index > 0) {
timeStamp = timeStamp.substring(0, index);
}
int indexGMT = timeStamp.indexOf("GMT");
int indexPlus = timeStamp.indexOf("+");
if (indexGMT > 0) {
dateTime = timeStamp.substring(0, indexGMT);
} else if (indexPlus > 0) {
dateTime = timeStamp.substring(0, indexPlus);
} else {
dateTime = timeStamp;
}
SimpleDateFormat sdfgmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfgmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat sdfmad = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdfmad.setTimeZone(TimeZone.getDefault());
Date gmtDate;
Date localDate = null;
try {
gmtDate = sdfgmt.parse(dateTime);
localDate = sdfmad.parse(sdfmad.format(gmtDate));
} catch (ParseException e) {
}
return localDate;
}
要获取当前的UNIX时间戳,可以使用以下代码
long unixTime = System.currentTimeMillis() / 1000L;
答案 1 :(得分:1)
尝试
科特琳
fun getDateTimeString( ): String {
val calendar = Calendar.getInstance()
calendar.timeZone= TimeZone.getDefault()
calendar.timeInMillis = Date().time
return SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(calendar.time)
}
JAVA
private String getDateTimeString(){
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(new Date().getTime());
return new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(calendar.getTime());
}
从Google获取时间:How to get current time from Google for Android?
try{
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(new HttpGet("https://google.com/"));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
String dateStr = response.getFirstHeader("Date").getValue();
//Here I do something with the Date String
System.out.println(dateStr);
} else{
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}catch (ClientProtocolException e) {
Log.d("Response", e.getMessage());
}catch (IOException e) {
Log.d("Response", e.getMessage());
}
答案 2 :(得分:0)
使用现代的 java.time 类。
获取JVM的当前默认时区。
ZoneId z = ZoneId.systemDefault() ;
或询问用户。
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
获取该地区人民使用的挂钟时间所显示的当前时刻。
ZonedDateTime zdt = ZonedDateTime.now( z ) ;
提取日期部分。
LocalDate ld = zdt.toLocalDate() ;
提取一天中的时间。
LocalTime lt = zdt.toLocalTime() ;
如果要进行更新,如果要使用现在可能是当前的任何区域再次收集当前时刻,只需重复上述步骤即可。 java.time 对象是不可变的,并且不会自动更新。您必须请求包含新数据的新对象。
ZonedDateTime.now( ZoneId.systmDefault() ).toLocalDate()