如何在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);

其他回答

科特林

下面是在Kotlin中获取当前日期时间的各种方法。

fun main(args: Array<String>) {
    println(System.currentTimeMillis()) // Current milliseconds

    val date = Calendar.getInstance().time // Current date object
    val date1 = Date(System.currentTimeMillis())

    println(date.toString())
    println(date1.toString())

    val now = Time(System.currentTimeMillis()) // Current time object
    println(now.toString())

    val sdf = SimpleDateFormat("yyyy:MM:dd h:mm a", Locale.getDefault())
    println(sdf.format(Date())) // Format current date

    println(DateFormat.getDateTimeInstance().format(System.currentTimeMillis())) // using getDateTimeInstance()

    println(LocalDateTime.now().toString()) // Java 8

    println(ZonedDateTime.now().toString()) // Java 8
}

这是一个获取日期和时间的有用方法:

private String getDate(){
    DateFormat dfDate = new SimpleDateFormat("yyyy/MM/dd");
    String date=dfDate.format(Calendar.getInstance().getTime());
    DateFormat dfTime = new SimpleDateFormat("HH:mm");
    String time = dfTime.format(Calendar.getInstance().getTime());
    return date + " " + time;
}

你可以调用这个方法来获取当前的日期和时间值:

2017/01//09 19:23

对于当前日期和时间,使用:

String mydate = java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime());

输出:

Feb 27, 2012 5:41:23 PM
    //currentTimeMillis is System.currentTimeMillis()

    long totalSeconds = currentTimeMillis / 1000;
    int currentSecond = (int)totalSeconds % 60;

    long totalMinutes = totalSeconds / 60;
    int currentMinute = (int)totalMinutes % 60;

    long totalHours = totalMinutes / 60;
    int currentHour = (int)totalHours % 12;

    TextView tvTime = findViewById(R.id.tvTime);
    tvTime.setText((currentHour + OR - TIME YOU ARE FROM GMT) + ":" + currentMinute + ":" + currentSecond);

试试这个

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