HttpUrlConnection connection=(HttpURLConnection)new URL("http://www.baidu.com").openConnection(); connection.connect(); long date = connection.getDate(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd",Locale.CHINA); format.setTimeZone(TimeZone.getTimeZone("GMT+08")); String dateString = format.format(new Date(date));
解釋一下,SimpleDateFormat的setTimeZone()方法可以設(shè)置指定的時(shí)區(qū)妹窖,如果僅是format.format(new Date())
收叶,得到的時(shí)間不受系統(tǒng)設(shè)置中時(shí)區(qū)設(shè)置的影響,但是會(huì)受設(shè)置的指定日期影響蜓萄,這時(shí)候我們可以從網(wǎng)絡(luò)連接上獲得一個(gè)不受系統(tǒng)設(shè)置影響的時(shí)間值傳到Date中的構(gòu)造方法去讓它構(gòu)造澄峰,這樣在代碼中得到的時(shí)間怎么都不會(huì)受系統(tǒng)設(shè)置的影響了.(為什么第一個(gè)空格會(huì)空出這么多)