2010-06-14 02:21:49 + 0400或2010-06-14 02:21:49-0400獲取設備的本地時區
有沒有辦法根據這個字符串轉換爲日期本地計算機時區與格式2010-06-14上午02點21
2010-06-14 02:21:49 + 0400或2010-06-14 02:21:49-0400獲取設備的本地時區
有沒有辦法根據這個字符串轉換爲日期本地計算機時區與格式2010-06-14上午02點21
添加到什麼@ org.life.java和@Erica說,這裏是你應該什麼不要
String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);
System.out.println(newDateStr);
然後newDateStr
將成爲新的日期格式的字符串。
UPDATE @xydev,我給你的工作,請參見下面的完整的源代碼的例子:
/**
*
*/
package testcases;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
/**
* @author The Elite Gentleman
*
*/
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
String dateStr = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
TimeZone tz = TimeZone.getDefault();
sdf.setTimeZone(tz);
Date date = sdf.parse(dateStr);
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss a");
String newDateStr = sdf.format(date);
System.out.println(newDateStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
輸出:2010-06-14 08:21:49 AM
String string1 = "2010-06-14 02:21:49-0400";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ")
sdf.setTimeZone(tz);
Date date = sdf.parse(string1);
注:我不知道同一個類可以在Andriod的。
您可以使用DateFormat類做各種各樣的花哨格式和日期的本地化。在這裏的API頁面開始處有非常好的完整文檔: http://download.oracle.com/javase/1.4.2/docs/api/java/text/DateFormat.html
大多數常規情況下都可以使用內置的SimpleDateFormat對象進行處理。它的細節在這裏: http://download.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html
你有上面的例子SimpleDateFormat的輸出模式字符串將是:
yyyy-MM-dd hh:mm a
要小心,如果你正在運行模擬器你的時區總是格林尼治標準時間。我花了2個小時試圖理解爲什麼我的應用程序沒有給我正確的時間(我的電腦顯示的那個),直到我意識到這是因爲模擬器。
檢查正在仿真器上運行,使用
if (Build.PRODUCT.contains("sdk")){
// your code here for example if curtime has the emulator time
// since midnight in milliseconds then
curtime += 2 * 60 * 60 * 1000; // to add 2 hours from GMT
}
[根據裝置的時區顯示日期](可能重複http://stackoverflow.com/questions/4312220/display-date-根據該設備的時區) – 2010-11-30 10:52:17
我剛剛回答了這個問題。 – 2010-11-30 10:52:39