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


当前回答

实际上,使用time . getcurrenttimezone()在设备上设置当前时区更安全,否则您将获得UTC的当前时间。

Time today = new Time(Time.getCurrentTimezone());
today.setToNow();

然后,你可以得到你想要的所有日期字段,例如:

textViewDay.setText(today.monthDay + "");             // Day of the month (1-31)
textViewMonth.setText(today.month + "");              // Month (0-11)
textViewYear.setText(today.year + "");                // Year 
textViewTime.setText(today.format("%k:%M:%S"));  // Current time

详情请参阅android.text.format.Time类。

更新

正如许多人指出的那样,谷歌说这个类有一些问题,不应该再使用了:

This class has a number of issues and it is recommended that GregorianCalendar is used instead. Known issues: For historical reasons when performing time calculations all arithmetic currently takes place using 32-bit integers. This limits the reliable time range representable from 1902 until 2037.See the wikipedia article on the Year 2038 problem for details. Do not rely on this behavior; it may change in the future. Calling switchTimezone(String) on a date that cannot exist, such as a wall time that was skipped due to a DST transition, will result in a date in 1969 (i.e. -1, or 1 second before 1st Jan 1970 UTC). Much of the formatting / parsing assumes ASCII text and is therefore not suitable for use with non-ASCII scripts.

其他回答

    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);

Use:

Time time = new Time();
time.setToNow();
System.out.println("time: " + time.hour + ":" + time.minute);

例如,这将为您提供“12:32”。

记得导入android.text.format.Time;。

试试这个

String mytime = (DateFormat.format("dd-MM-yyyy hh:mm:ss", new java.util.Date()).toString());

你可以用:

import java.util.Calendar;
import java.util.Date;

Date currentTime = Calendar.getInstance().getTime();

Calendar中有许多常量可以满足您的所有需要。

检查Calendar类文档。

final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);

textView.setText("" + mDay + "-" + mMonth + "-" + mYear);