android中获取时间
? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?android中獲取時間
?
1)通過calendar類獲取
Calendar calendar = Calendar.getInstance();
int moth = calendar.get(Calendar.MONTH);
int date = calendar.get(Calendar.DATE);
int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
?
2)未知方法
獲取當前時間:System.currentTimeMillis()??? 獲得的是從1970年1月1日到當前時間的總秒數
獲取時區:TimeZone.getDefault();
舉例說明:
例1:
Calendar now = Calendar.getInstance();
??? TimeZone timeZone = now.getTimeZone();
????
long totalMilliseconds = System.currentTimeMillis() + timeZone.getRawOffset();
??? long totalSeconds = totalMilliseconds / 1000;
??? int currentSecond = (int)(totalSeconds % 60);
??? long totalMinutes = totalSeconds / 60;
??? int currentMinute = (int)(totalMinutes % 60);
??? long totalHours = totalMinutes / 60;
??? int currentHour = (int)(totalHours % 24);
??? int totalDays = (int)(totalHours / 24);
??? int goDays = 0;
??? int surplusDays = 0;
??? int goYears = 0;
??? int leapyear = 0;
??? for(int i = 1970;goDays<totalDays;i++)
??? {
???? if(i%400==0||(i%4==0&&i%100!=0))
????? {goDays = goDays+366; leapyear = 1;}
???? else {goDays = goDays +365; leapyear = 0;}
???? goYears++;
??? }
??? String output = "Current time is " + currentHour + ":"
????? + currentMinute + ":" + currentSecond + " GMT"+(1970+goYears-1);
??? JOptionPane.showMessageDialog(null, output);
例2:
long l = System.currentTimeMillis();
? Date date = new Date(l);
? Calendar cal = Calendar.getInstance();
? cal.setTime(date);
? System.out.println(cal.get(Calendar.YEAR));
? System.out.println(cal.get(Calendar.MONTH) + 1);// 月份計算是從0作為1開始的。
? System.out.println(cal.get(Calendar.DATE));
? System.out.println(cal.get(Calendar.HOUR));
? System.out.println(cal.get(Calendar.MINUTE));
? System.out.println(cal.get(Calendar.SECOND));
?
3)通過java包獲得時間
?public void getTime(){
? ? ? ? ? ? time = (TextView) findViewById(R.id.test_1);
? ?? ???java.util.Date date = new java.util.Date();
? ?? ???time.setText(date.toString());
? ? }
加背景顏色的可以改成toLocalString()或者toGMTString()
三者的區別(格式)是:(1),toSting():Tue Sep 20 07:56:00 GMT+00:00 2011
????????????????????????????????? (2),toLocaleString():Sep 20,2011 08:00:00 AM? (這種格式比較適合大眾)
????????????????????????????????? (3),toGMTString():20 Sep 2011 08:00:00 GMT
4),最簡單的,通過android自帶的空間完成時鐘的添加
分別是AnalogClock機械時鐘和DigitalClock數字時鐘,只需要在android的xml布局文件中添加兩個空間即可
摘自:http://hi.baidu.com/diyangxia/item/43e4390a12946bcfdde5b0a2?
轉載于:https://www.cnblogs.com/Sharley/p/5729066.html
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的android中获取时间的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Elasticsearch + Logs
- 下一篇: c++ 走向高级之日积月累