如何获取当前时间并使其成为textview

How to get current time and make it textview

我正在尝试获取当前时间并将其设为文本视图。我发现的是 10 或 12 岁的,我真的不知道那是否有效以及它是如何工作的。我看到您可以使用 firebase 和其他网站或应用程序。我想得到一些帮助。

Link

我找到的一些代码

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

Calendar.getInstance().get(Calendar.HOUR_OF_DAY);

Calendar.getInstance().get(Calendar.MINUTE);

谢谢大家

仅限当前时间

long currentDateTime = System.currentTimeMillis();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
        String currentTime = simpleDateFormat.format(currentDateTime);
        Toast.makeText(this, currentTime, Toast.LENGTH_SHORT).show();

如果您同时需要日期和时间,那么下面的代码适合您

        long currentDateTime = System.currentTimeMillis();
        @SuppressLint("SimpleDateFormat") SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy  h:mm a");
        String currentDateTime = simpleDateFormat.format(currentDateTime);
        Toast.makeText(this, currentDateTime, Toast.LENGTH_SHORT).show();

编辑 1 另一种方法

LocalDateTime myDt= LocalDateTime.now();
        Toast.makeText(this, myDt.getHour()+":"+myDt.getMinute()+":"+myDt.getSecond(), Toast.LENGTH_SHORT).show();

编辑 2 另一种获取日期的方法

LocalDateTime myDt= LocalDateTime.now();
        DateTimeFormatter newDt = DateTimeFormatter.ISO_DATE;
        String dates = newDt.format(myDt);
        Toast.makeText(this,dates, Toast.LENGTH_LONG).show();

通过从 ISO_DATE 更改为 ISO_DATE_TIMEISO_LOCAL_DATE_TIME 等,您可以获得更多选项来获取日期、时间、格林威治标准时间等。