[英]how to convert Date object to string/long and send it via client/server
[英]How to convert a string Date to long millseconds
我在字符串中有一个日期,类似于“2012年12月12日”。 如何将其转换为毫秒(长)?
String string_date = "12-December-2012";
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
try {
Date d = f.parse(string_date);
long milliseconds = d.getTime();
} catch (ParseException e) {
e.printStackTrace();
}
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
Date date = (Date)formatter.parse("12-December-2012");
long mills = date.getTime();
看一下SimpleDateFormat
类,它可以解析String
并返回Date
和Date
类的getTime
方法。
现在是时候有人为这个问题提供了现代答案。 在2012年问到这个问题的时候,那些回答的答案也是很好的答案。 为什么2016年发布的答案也使用当时很久的过时类SimpleDateFormat
和Date
对我来说有点神秘。 java.time
,现代Java日期和时间API,也称为JSR-310,使用起来非常好。 您可以通过ThreeTenABP在Android上使用它,请参阅此问题:如何在Android项目中使用ThreeTenABP 。
对于大多数用途,我建议使用自UTC时间开始的纪元以来的毫秒数。 要获得这些:
DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("d-MMMM-uuuu", Locale.ENGLISH);
String stringDate = "12-December-2012";
long millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli();
System.out.println(millisecondsSinceEpoch);
这打印:
1355270400000
如果您需要在某个特定时区的某天开始时间,请指定该时区而不是UTC,例如:
.atStartOfDay(ZoneId.of("Asia/Karachi"))
正如预期的那样,结果略有不同:
1355252400000
还有一点需要注意,请记住为DateTimeFormatter
提供一个语言环境。 我把12月份当作英语,还有其他语言,那个月被称为相同,所以请自己选择合适的语言环境。 如果您没有提供语言环境,格式化程序将使用JVM的语言环境设置(在许多情况下可能有效),然后在具有不同语言环境设置的设备上运行应用程序时出现意外故障。
您可以使用simpleDateFormat来解析字符串日期。
使用simpledateformat您可以轻松实现它。
1)首先使用simpledateformatter将字符串转换为java.Date。
2)使用getTime方法从日期获得毫秒数
public class test {
public static void main(String[] args) {
String currentDate = "01-March-2016";
SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy");
Date parseDate = f.parse(currentDate);
long milliseconds = parseDate.getTime();
}
}
更多示例请单击此处
最简单的方法是使用Date Using Date()和getTime()
Date dte=new Date();
long milliSeconds = dte.getTime();
String strLong = Long.toString(milliSeconds);
System.out.println(milliSeconds)
试试下面的代码
SimpleDateFormat f = new SimpleDateFormat("your_string_format", Locale.getDefault());
Date d = null;
try {
d = f.parse(date);
} catch (ParseException e) {
e.printStackTrace();
}
long timeInMillis = d.getTime();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.