我有时间milliseconds
,现在我想和这些分开 。time
date
milliseconds
我怎样才能做到这一点???
你可以这样使用
Calendar cl = Calendar.getInstance();
cl.setTimeInMillis(milliseconds); //here your time in miliseconds
String date = "" + cl.get(Calendar.DAY_OF_MONTH) + ":" + cl.get(Calendar.MONTH) + ":" + cl.get(Calendar.YEAR);
String time = "" + cl.get(Calendar.HOUR_OF_DAY) + ":" + cl.get(Calendar.MINUTE) + ":" + cl.get(Calendar.SECOND);
这个函数会给你一个毫秒的字符串日期
public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds)
{
Date date = new Date();
date.setTime(timestampInMilliSeconds);
String formattedDate=new SimpleDateFormat("MMM d, yyyy").format(date);
return formattedDate;
}
转换milliseconds
为Date
实例并将其传递给所选的格式化程序:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
String myDate = dateFormat.format(new Date(dateInMillis)));
您可以将毫秒转换为日期对象,然后以时间字符串和另一个仅包含日期的字符串的格式提取日期
使用Calendar获取不同时间字段的值:
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timeInMillis);
int dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
int monthOfYear = cal.get(Calendar.MONTH);
对 Kiran Kumar 的进一步回答
public static String getFormattedDateFromTimestamp(long timestampInMilliSeconds, String dateStyle){
Date date = new Date();
date.setTime(timestampInMilliSeconds);
String formattedDate=new SimpleDateFormat(dateStyle).format(date);
return formattedDate;
}
我建议 java.time,现代 Java 日期和时间 API,用于您的日期和时间工作:
long millisecondsSinceEpoch = 1_567_890_123_456L;
ZonedDateTime dateTime = Instant.ofEpochMilli(millisecondsSinceEpoch)
.atZone(ZoneId.systemDefault());
LocalDate date = dateTime.toLocalDate();
LocalTime time = dateTime.toLocalTime();
System.out.println("Date: " + date);
System.out.println("Time: " + time);
我的时区(欧洲/哥本哈根)的输出:
Date: 2019-09-07 Time: 23:02:03.456
其他答案中使用的日期和时间类 -和Calendar
-设计不佳且早已过时。这就是为什么我不建议使用它们中的任何一个,而是更喜欢 java.time。Date
SimpleDateFormat
java.time 在较旧和较新的 Android 设备上都能很好地工作。它只需要至少Java 6。
org.threeten.bp
子包中导入日期和时间类。java.time
第一次描述的地方。java.time
Java 6 和 7 的反向移植(ThreeTen for JSR-310)。您可以使用日期格式并将您的毫秒值设置为此构造函数的参数,遵循以下代码:
SimpleDateFormat SDF= new SimpleDateFormat("dd/MM/yyyy");
String date = SDF.format(new Date(millies)));