Android: Getting the current date and time

杀马特。学长 韩版系。学妹 提交于 2020-01-25 09:01:12

问题


I am trying to get the today's date and time using the following code,

SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy HH:mm");
String currentDateandTime = sdf.format(new Date());

but the outcome is

26/15/2014 13:15 instead of 26/1/2014 13:15

What is wrong?

Thanks!


回答1:


Replace first mm with MM. Check documentation at http://developer.android.com/reference/java/text/SimpleDateFormat.html

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String currentDateandTime = sdf.format(new Date());



回答2:


replace dd/mm/yyyy

by dd/MM/yyyy

capital M for month small m for minute

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");
String currentDateandTime = sdf.format(new Date());



回答3:


Your formatting is wrong "dd/mm/yyyy HH:mm" it should be "dd/MM/yyyy HH:mm", Notice the MM

Instead of SimpleDateFormat use DateFormat

Because SimpleDateFormat is Depreciated though

android.text.format.DateFormat dateFormat= new android.text.format.DateFormat();
dateFormat.format("dd/MM/yyyy HH:mm", new java.util.Date());



回答4:


You should use right format

H hours m minutes s seconds S fractions of Second a am/pm marker d day of the month M month of the year y year w week of year

 String[] formats = new String[] {
   "yyyy-MM-dd",
   "yyyy-MM-dd HH:mm",
   "yyyy-MM-dd HH:mmZ",
   "yyyy-MM-dd HH:mm:ss.SSSZ",
   "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
 };
 for (String format : formats) {
   SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
   System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.out.format("%30s %s\n", format, sdf.format(new Date(0)));
 }

and the output is

                 yyyy-MM-dd 1969-12-31
                 yyyy-MM-dd 1970-01-01
           yyyy-MM-dd HH:mm 1969-12-31 16:00
           yyyy-MM-dd HH:mm 1970-01-01 00:00
          yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800
          yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000
   yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800
   yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000
 yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800
 yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000

Which produces the above output when run in the America/Los_Angeles time zone:

know more from here




回答5:


Use M instead of m for the month. m means minutes http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html



来源:https://stackoverflow.com/questions/21360036/android-getting-the-current-date-and-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!