版权声明:欢迎转载,注明出处就好!! https://blog.csdn.net/u011043551/article/details/53129329
日期时间的获取方式如下所示:
1、使用SimpleDateFormat和Date类获取日期时间
private String _GetYear(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); String s = sdf.format(new Date()); return s; } private String _GetMonth(){ SimpleDateFormat sdf = new SimpleDateFormat("MM"); String s = sdf.format(new Date()); return s; } private String _GetDays(){ SimpleDateFormat sdf = new SimpleDateFormat("dd"); String s = sdf.format(new Date()); return s; }2、使用Calendar类获取日期时间
private String _GetDate(){ TimeZone tz = TimeZone.getTimeZone("GMT"); Calendar c = Calendar.getInstance(tz); return "year = "+c.get(Calendar.YEAR)+"\n month = "+c.get(Calendar.MONTH)+"\n day = "+c.get(Calendar.DAY_OF_MONTH); }
3、使用Time类获取日期时间
private String _GetDateFromTime(){ Time t = new Time(); t.setToNow(); return "year = "+t.year+"\n month = "+t.month+"\n day = "+t.monthDay; }
当前系统的日期是:2016 11 11
三种不同方式获取的日期如下:
11-11 15:34:00.220 23527-23527/com.example.datedemo I/zyq_time: SimpleDateFormat : year = 2016
month = 11
day = 11
11-11 15:34:00.223 23527-23527/com.example.datedemo I/zyq_time: Calendar : year = 2016
month = 10
day = 11
11-11 15:34:00.224 23527-23527/com.example.datedemo I/zyq_time: Time : year = 2016
month = 10
day = 11
打印出来的结果存在区别,通过SimpleDateFormat方式打印出来的日期是正确的,其他两种方式获取的月份比实际月份小1
MainActivity.java
package com.example.datedemo; import android.icu.util.Calendar; import android.icu.util.TimeZone; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.format.Time; import android.util.Log; import android.util.TimeUtils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } private String _GetYear(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); String s = sdf.format(new Date()); return s; } private String _GetMonth(){ SimpleDateFormat sdf = new SimpleDateFormat("MM"); String s = sdf.format(new Date()); return s; } private String _GetDays(){ SimpleDateFormat sdf = new SimpleDateFormat("dd"); String s = sdf.format(new Date()); return s; } private String _GetDate(){ TimeZone tz = TimeZone.getTimeZone("GMT"); Calendar c = Calendar.getInstance(tz); return "year = "+c.get(Calendar.YEAR)+"\n month = "+c.get(Calendar.MONTH)+"\n day = "+c.get(Calendar.DAY_OF_MONTH); } private String _GetDateFromTime(){ Time t = new Time(); t.setToNow(); return "year = "+t.year+"\n month = "+t.month+"\n day = "+t.monthDay; } @Override protected void onResume() { super.onResume(); Log.i("zyq_time","SimpleDateFormat : year = "+_GetYear()+"\n month = "+_GetMonth()+"\n day = "+_GetDays()); Log.i("zyq_time","Calendar : "+_GetDate()); Log.i("zyq_time","Time : "+_GetDateFromTime()); } }