【问题标题】:When i press a button how to get time at that time and set to a text field当我按下按钮时如何获取时间并设置为文本字段
【发布时间】:2017-12-28 21:59:09
【问题描述】:

我正在尝试创建一个聊天应用程序(移动应用程序)。当我按下发送按钮时,我需要将此刻的时间设置为文本视图

【问题讨论】:

  • 这个问题的每一部分都很容易用谷歌搜索。例如,“获取 Java 中的当前时间”或“响应 Android 中的按钮点击”。
  • 我不想使用当前时间我想在按下按钮的那一刻得到时间
  • 我不明白其中的区别。
  • 在按钮调用 System.currentTimeMillis() 的 onClick 方法中,您将获得按下按钮的时间。

标签: android android-studio-2.3


【解决方案1】:
    Button button = findViewById(R.id.button);
    button.setOnClickListener(v -> {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat(" d MMM yyyy HH:mm:ss ");
        String time =  format.format(calendar.getTime());

        TextView textView = findViewById(R.id.cdt);
        textView.setText(time);
    });

}

}

【讨论】:

    【解决方案2】:

    你可以试试这个对你有帮助

     Calendar calendar = Calendar.getInstance();
        int a = calendar.get(Calendar.AM_PM);
        String time;
        if(a == Calendar.AM) {
         time = calendar.get(Calendar.HOUR)+":"+calendar.get(Calendar.MINUTE)+"AM";
        }
        else {
            time = calendar.get(Calendar.HOUR)+ ":"+calendar.get(Calendar.MINUTE)+"PM";
        }
        textView.setText(time);
    

    【讨论】:

      【解决方案3】:

      您可以尝试以下操作:

      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
      YOUR_TEXT_VIEW.setText(sdf.format(new Date(System.currentTimeMillis()));
      

      【讨论】:

      • 他希望设置时间,而您的日期格式只设置日期而不设置时间。
      • 您也可以简单地添加 HH:mm:ss 来获取时间
      • @HemalHerath 请编辑您的问题以准确显示您的尝试。还要显示结果是什么,并说明与您想要的不同。
      【解决方案4】:

      您只需从系统获取当前日期和时间,然后显示在您的文本视图上。试试这个 -

      SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
      your_textView.setText(dateFormat.format(new Date());
      

      【讨论】:

      • 我需要用现在的时间不想用实时
      • 现在的时间是什么意思?它与实时有何不同
      • 设置时间后我不想更新时间
      • 为什么它会更新时间,直到你再次执行 textview settext?如果您想在某处节省时间,请在单击按钮时将其与聊天消息一起保存在模型对象中,并在文本视图中显示该时间
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多