2012-10-20 30 views
1

這就是我如何得到手機的日期,但它提示我一個parseException,有什麼問題?如何獲取android手機的當前日期?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); 
    String date = sdf.format(new Date()); 
    Date localDate = sdf.parse(date); 
+0

當我寫它 – Blake

+0

是的,仍然是相同的錯誤 – Blake

回答

3

new Date(0)不是當前日期/時間。你應該使用new Date()。那麼ParseException應該消失。如果你想知道你爲什麼得到它,只需調試你的程序,並看看新的Date(0)給出了什麼樣的String,你就會知道爲什麼它不能被解析。

Date now = new Date(); 
Date alsoNow = Calendar.getInstance().getTime(); 
String nowAsString = new SimpleDateFormat("yyyy-MM-dd").format(now); 

這是有效的。而這也:

Date christmas = new SimpleDateFormat("yyyy-MM-dd").parse("2012-12-25"); 

順便說一句,請確保您使用java.util.Date而不是java.sql.Date

+0

新日期()也不工作。 – Blake

+1

我想錯誤是我想要的日期類型,而不是字符串 – Blake

+0

不,也可以工作 –

-1
Date dt = new Date(); 
        int hours = dt.getHours(); 
        int minutes = dt.getMinutes(); 
        int seconds = dt.getSeconds(); 
        String curTime = hours + ":" + minutes + ":" + seconds; 

然後還要在這裏是這個 Display the current time and date in an Android application

+1

-1,因爲所有這些方法都被棄用了。可以使用日曆來獲取單獨的字段,也可以使用DateFormat格式化日期。 –

1
Calendar now = Calendar.getInstance(); 
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); 
String nowDate = formatter.format(now.getTime()); 
String[] separateCurrentDate = nowDate.split("-"); 
String year = separateCurrentDate[0]; 
String month = separateCurrentDate[1]; 
String day = separateCurrentDate[2]; 
int currentYear = Integer.parseInt(year); 
int currentMonth = Integer.parseInt(month); 
int currentDay = Integer.parseInt(day); 

和另一個鏈接然後將y,m,d逐個存入Date對象

1
Date now = new Date(); 
    Date alsoNow = Calendar.getInstance().getTime(); 
    String nowAsString = new SimpleDateFormat("yyyy-MM-dd").format(now); 
    currentdate = (TextView)findViewById(R.id.textcntdate); 
    currentdate.setText(nowAsString); 
相關問題