Sunday, 7 July 2019

ISO 8601 date format to Unix Time in Java




I have done some Googling and Stacking, but cannot find the necessary resources for any methods that can convert ISO-8601 format to Unix time in Java.




I am parsing NOAA's (National Oceanic Atmospheric Administration) predictions, and using XPath I am able to successfully parse that data. I would, however, like to convert the ISO-8601 i.e. 2013-10-31T14:00:00-07:00 date format to Unix time.



Are there any Java libraries that can do this?



What my code does:



for (int i = 0; i < tempHourlyResult.getLength(); i++) {
writer.append(
hourlyResult.item(i).getNodeValue() + ","
+ tempHourlyResult.item(i).getNodeValue()+ ","

+ dewPointResult.item(i).getNodeValue() + ","
+ windSpeedResult.item(i).getNodeValue() +","
+ relHumResult.item(i).getNodeValue() + "\n");
}

Answer



The java.util.Date class store time internally in a format very close to the POSIX time format (it uses milliseconds instead of seconds). So assuming you have your date in a String object called stringDate:



SimpleDateFormat dateParser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
long dateInMilli = dateParser.parse(stringDate).getTime();

long posixDate = dateInMilli/1000

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...