Java:以“ hh:MM:ss a”格式获取时间

时间:2019-07-04 09:19:21

标签: java android date android-studio

我正在构建一个Android应用程序,并且在我的项目中使用Date类来获取当前日期。我用simpledateformatter格式化了日期,并像dd-mm-yyyy一样显示了日期(即日,年,年)。

现在我也想以hh:MM:ss a(小时分钟秒AM / PM)的时间获取时间

当我使用日期实例时,我看到它也显示日期和时间(默认格式)。所以我试图从日期的实例中获取时间。(假设d是日期类的实例)。我还找到了日期类的getTime()方法并执行了d.getTime(),但返回的时间很长(这是从过去的某个固定时间到当前时间的持续时间)。现在我想以所需的格式显示时间,但是这种getTime()方法给了我很多时间。

请为我提供一些有关如何处理此long值的方法,以期获得所需的时间格式。例如,d.getTime()向我返回了一些值(例如11233),而我想要这样的格式(11:33:22)。

3 个答案:

答案 0 :(得分:2)

您可以做到

private final String DATE_FORMAT = "dd.MM.yyyy HH:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
Date got = sdf.parse(date);

它向您返回带时间的日期

答案 1 :(得分:1)

使用此代码片段同时获取datetime

public String currentDateTime() {
    Calendar c = Calendar.getInstance();
    SimpleDateFormat dateformat = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss aa");  //it will give you the date in the formate that is given in the image
    String datetime = dateformat.format(c.getTime()); // it will give you the date
    return datetime;
}

注意:查看图像enter image description here

答案 2 :(得分:1)

Date()。getTime()为您提供时间戳记

根据您的要求更改格式,例如mm:hh:ss a

科特琳

fun getDateTime():String {
    val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault())
    val date = Date()
    return inputFormat.format(date.time)
}

JAVA

private String getDateTime(){
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.getDefault());
        return format.format(new Date().getTime());
    }