Scala parse almost ISO Datetime String with TimeZone adjustment

Scala Example to parse almost ISO Date time string,  convert to proper time zone and regenerate as ISO standard string.
See Also: Helpful Scala Resource Links

  To Compile:
     scalac exParseISOTimeStr.scala
  To Run:
     scala exParseISOTimeStr
// exParseISOTimeStr.scala
 
import java.time._
import java.time.format.DateTimeFormatter
 
object exParseISOTimeStr {
 def main(args: Array[String]){
 println("exParseISOTime")
 val barDateTime = "2014-01-27 13:21:00.000" // assume EST due to stock data source
 println("starting datesTimeStr=s" + barDateTime);
 
 // Simple parse only the date 
 val simpDate = LocalDate.parse("2015-01-27");
 System.out.printf("Simple Date %s\n", simpDate);
 
 // parse Bar format which is almost ISO
 // using custom format string 
 // assumes it is local time.
 val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")
 val barDate1 = LocalDateTime.parse(barDateTime,formatter);
 System.out.printf("barDate1 %s\n", barDate1);
 
 val aFmtStr1 = barDate1.format(formatter); // Convert back original format
 val asISOStr1 = barDate1.toString(); // Convert back to ISO format
 System.out.printf("adTimex1 format=%s almostISO=%s\n", aFmtStr1, asISOStr1);
 
 // Parse Bar format but properly handle the 
 // fact the bar Times are supplied in EST
 // we need to reflect this or it can make future
 // time comparisons for servers running in PST
 // incorrect.
 val barDate2 = LocalDateTime.parse(barDateTime,formatter);
 val zoneTimex2 = barDate2.atZone(ZoneId.of("EST", ZoneId.SHORT_IDS))
 // tell the system that time is actually in EST time zone
 System.out.printf("zonedTime asISO=%s\n", zoneTimex2.toString());
 
 // Convert the timezone adjusted time to ISO Time
 // string then re-parse it.
 val zoneTimeStr = zoneTimex2.toString();
 val rpZoneTime = ZonedDateTime.parse(zoneTimeStr);
 System.out.printf("time asIOS=%s reParsedTime=%s\n", zoneTimeStr,rpZoneTime); 
 }
}

SEE ALSO:

  • https://www.hackingnote.com/en/scala/datetime/
    Uses SimpleDateFormat rather than DateTimeFormatter
  • http://queirozf.com/entries/java-8-timezones-examples-in-scala
    Explains zoned Date time
  • http://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html
    Java Date Time package documentation
  • http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
    Documents Date Time Formats

We offer expert consulting services

We offer consulting services with deep expertise in Search, Machine Learning, Distributed Architecture and High performance sites.   We specialize in solving the hardest problems you have available. Please contact us if you need engineering help.  joeeatbayesanalyticphone number

Leave a Reply