我正在添加这个问题,因为我是Java和Android的新手,我搜索了几个小时试图解决这个问题.答案来自相关答案的组合,所以我想我会记录我为其他可能正在努力的人学到的东西.见答案.
对于一些背景知识,我的经验主要是PHP的Web开发和一点Ruby.我唯一的操作系统是Linux(Ubuntu Studio),我(不情愿地)在Android Studio 2.1.2中开发我的第一个Android应用程序.我的Java设置如下:
>java -version
> openjdk version "1.8.0_91"
> OpenJDK Runtime Environment (build 1.8.0_91-8u91-b14-3ubuntu1~15.10.1-b14)
> OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)
Run Code Online (Sandbox Code Playgroud) datetime android android-gradle-plugin threetenbp threetenabp
我有一个包含UNIX Epoch时间的字符串,我需要将其转换为Java Date对象.
String date = "1081157732";
DateFormat df = new SimpleDateFormat(""); // This line
try {
Date expiry = df.parse(date);
} catch (ParseException ex) {
ex.getStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
标记的线是我遇到麻烦的地方.我无法弄清楚SimpleDateFormat()的参数应该是什么,或者即使我应该使用SimpleDateFormat().
我的Spring应用程序中有一个REST端点,如下所示
@RequestMapping(value="/customer/device/startDate/{startDate}/endDate/{endDate}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public Page<DeviceInfo> getDeviceListForCustomerBetweenDates(@PathVariable ZonedDateTime startDate, @PathVariable ZonedDateTime endDate, Pageable pageable) {
... code here ...
}
Run Code Online (Sandbox Code Playgroud)
我试过传递路径变量作为毫秒和秒.但是,我从两个方面得到以下异常:
"Failed to convert value of type 'java.lang.String' to required type 'java.time.ZonedDateTime'; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type java.lang.String to type @org.springframework.web.bind.annotation.PathVariable java.time.ZonedDateTime for value '1446361200'; nested exception is java.time.format.DateTimeParseException: Text '1446361200' could not be parsed at index 10"
Run Code Online (Sandbox Code Playgroud)
有人可以解释我如何传入(如秒或毫秒)字符串,如1446361200,并让它转换为ZonedDateTime?
或者是作为String传递然后自己进行转换的唯一方法?如果是这样,有一种通用的方法来处理具有类似设计的多种方法吗?
我试图将时间戳转换为人类可读的日期和时间.我试过了:
String dateSt = 1386580621268;
Log.i("*****", "date st is = "+dateSt);
long unixSeconds = Long.parseLong(dateSt);
Log.i("*******", "unix seconds is = "+unixSeconds);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy"); // the format of your date
String formattedDate = sdf.format(date);
System.out.println(formattedDate);
Run Code Online (Sandbox Code Playgroud)
09-12-2013不过,我得到了预期的结果28-12-45908.上面的例子可以在以下位置找到:将Unix时间戳转换为日期java,由David Hofmann回答
android ×2
java ×2
android-date ×1
date ×1
datetime ×1
java-time ×1
spring ×1
spring-mvc ×1
threetenabp ×1
threetenbp ×1
timestamp ×1