如何在Android应用程序中获取当前时间和日期?


当前回答

您可以从日历中单独获取时间和日期。

// You can pass time zone and Local to getInstance() as parameter

Calendar calendar = Calendar.getInstance();

int currentHour = calendar.get(Calendar.HOUR_OF_DAY);
int currentMinute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
int date = calendar.get(Calendar.DAY_OF_MONTH);
int month = calendar.get(Calendar.MONTH);
int year = calendar.get(Calendar.YEAR);

其他回答

试着用简单的方法获取当前的日期和时间:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
String currentDateandTime = sdf.format(new Date());

你可以简单地使用下面的代码:

 DateFormat df = new SimpleDateFormat("HH:mm"); // Format time
 String time = df.format(Calendar.getInstance().getTime());

 DateFormat df1 = new SimpleDateFormat("yyyy/MM/dd"); // Format date
 String date = df1.format(Calendar.getInstance().getTime());

你可以(但不再应该-见下文!)使用android.text.format.Time:

Time now = new Time();
now.setToNow();

从上面的参考链接:

Time类是一个更快的替代品 为java.util.Calendar和 java.util.GregorianCalendar类。 Time类的实例 表示指定的时间点 精准度第二。


注1: 我写这个答案已经有好几年了, 它是关于一个旧的,android专用的,现在已被弃用的类。 谷歌现在这样说 “他的类有一些问题,建议使用公历代替”。


注2:尽管Time类有一个toMillis(ignoreDaylightSavings)方法,但这只是为了方便传递给以毫秒为单位的方法。时间值仅精确到一秒;毫秒部分总是000。如果在循环中,你会这样做

Time time = new Time();   time.setToNow();
Log.d("TIME TEST", Long.toString(time.toMillis(false)));
... do something that takes more than one millisecond, but less than one second ...

结果序列将重复相同的值,例如1410543204000,直到下一秒开始,此时1410543205000将开始重复。

Android中的当前时间和日期格式

Calendar c = Calendar.getInstance();
System.out.println("Current dateTime => " + c.getTime());
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate = df.format(c.getTime());
System.out.println("Format dateTime => " + formattedDate);

输出

I/System.out: Current dateTime => Wed Feb 26 02:58:17 GMT+05:30 2020
I/System.out: Format dateTime => 26-02-2020 02:58:17 AM
    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    Calendar cal = Calendar.getInstance();
    System.out.println("time => " + dateFormat.format(cal.getTime()));

    String time_str = dateFormat.format(cal.getTime());

    String[] s = time_str.split(" ");

    for (int i = 0; i < s.length; i++) {
         System.out.println("date  => " + s[i]);
    }

    int year_sys = Integer.parseInt(s[0].split("/")[0]);
    int month_sys = Integer.parseInt(s[0].split("/")[1]);
    int day_sys = Integer.parseInt(s[0].split("/")[2]);

    int hour_sys = Integer.parseInt(s[1].split(":")[0]);
    int min_sys = Integer.parseInt(s[1].split(":")[1]);

    System.out.println("year_sys  => " + year_sys);
    System.out.println("month_sys  => " + month_sys);
    System.out.println("day_sys  => " + day_sys);

    System.out.println("hour_sys  => " + hour_sys);
    System.out.println("min_sys  => " + min_sys);