如何以dd/MM/yyyy格式返回java.util.Date



我使用此代码以特定模式显示时间。但三周后,我想以正常模式显示时间,使用简单的时间格式。下面是我迄今为止尝试过的代码:

}
static class TimeAgo {
private static final int SECOND_MILLIS = 1000;
private static final int MINUTE_MILLIS = 60 * SECOND_MILLIS;
private static final int HOUR_MILLIS = 60 * MINUTE_MILLIS;
private static final int DAY_MILLIS = 24 * HOUR_MILLIS;
private static final int WEEK_MILLIS = 7 * DAY_MILLIS ;

public static String getTimeAgo(long time) {
if (time < 1000000000000L) {
time *= 1000;
}
long now = System.currentTimeMillis();
if (time > now || time <= 0) {
return null;
}

final long diff = now - time;
if (diff < MINUTE_MILLIS) {
return "Justo ahora";
} else if (diff < 2 * MINUTE_MILLIS) {
return "Hace 1 minuto";
} else if (diff < 50 * MINUTE_MILLIS) {
return "Hace " + diff / MINUTE_MILLIS + " minutos";
} else if (diff < 90 * MINUTE_MILLIS) {
return "Hace una hora";
} else if (diff < 24 * HOUR_MILLIS) {
return "Hace " + diff / HOUR_MILLIS + " horas";
} else if (diff < 48 * HOUR_MILLIS) {
return "Ayer";
} else if (diff < 72 * HOUR_MILLIS) {
return "Hace un día";
} else if (diff < 7 * DAY_MILLIS) {
return "Hace " + diff / DAY_MILLIS + " días";
} else if (diff < 2 * WEEK_MILLIS) {
return "Hace una semana";
} else if (diff < WEEK_MILLIS * 3) {
return "Hace " + diff / WEEK_MILLIS + " semanas";
} else {
java.util.Date date = new java.util.Date((long) time); return date.toString();
}
}
}
{

但它没有返回所需的时间格式。任何帮助都将不胜感激。

我真的建议您使用java.time API,因为Date类大多不推荐使用

所以现在你可以使用java.time.format.DateTimeFormatter

这是一个基本的例子,我还假设你正在写下面的代码,我正在类中使用,例如Main方法。所以你可以自己导入库

LocalDate date = 
your_date_.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
DateTimeFormatter dtformat = DateTimeFormatter.offPattern("dd/MM/yyyy");
YourDate = dtformat.format(date);
System.out.println(YourDate);

使用此设置日期格式:

SimpleDateFormat timeFormat = new SimpleDateFormat("dd/MM/yyyy", Locale.US);
String formattedDate;
Calendar calendar = Calendar.getInstance(); 
calendar.setTimeInMillis(timeInMillis); // timeInMillis should be in milliseconds
Date calendarTime = calendar.getTime(); 
formattedDate = timeFormat.format(calendarTime);

如果你想制作2021年10月21日这样的日期甲酸酯,你可以使用以下方法:

private String getReadableDateTime(Date date) {
return new SimpleDateFormat("dd-MM-yyyy" , Locale.getDefault()).format(date);
}

然后当你想获得当前日期时,调用类似的方法

getReadableDateTime(new Date());

它会给你你想要的甲酸酯。此外,如果你想与PM或AM相处,请使用此"dd-MM-yyyy - hh:mm a"

已经解决了问题。我只需要改变一下:

java.util.Date date = new java.util.Date((long) time); return date.toString();

插入以下内容:

java.text.SimpleDateFormat f = new java.text.SimpleDateFormat("dd/MM/yyyy");
return f.format(time);

最新更新