DateTimeFormat/DateTimeFormatter

I think I have spent several hours on what I think is a simple implementation of these classes in OH, so I want to ask for help.

I want to use the joda-time to read a string that follows a simple date-time pattern. Naturally I am using the DateTimeFormat/DateTimeFormatter to setup the pattern.

import org.joda.time.*
var String sDateOff = "04/11/2016 05:50"
var DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm")
var DateTime dtAlarm = dtf.parseDateTime(sDateTimeOff)

And we have an error:
[ERROR] [o.o.c.s.ScriptExecutionThread ] - Error during the execution of rule 'Simple Rule': The name 'DateTimeFormat' cannot be resolved to an item or type.

So what is the missing piece here?

EDIT: Added reference

I want to do the same, but i cannot access the DateTimeFormat and DateTimeFormatter classes from OH1 IDE, because OH can’t resolve these classes when you use it in rules. So I made the following workaround:

//create a java date formatter
val SimpleDateFormat dateFormatter = new SimpleDateFormat( "YYYY-MM-dd HH:mm:ss" )
//parse the date with java date formatter, and pass it to joda time DateTime constructor... 
var DateTime origStartDate = new DateTime(dateFormatter.parse("2016-08-05 20:37:47"))

Or you can use the parse command (yoda time parse):

 var DateTime origEndDate = parse("2016-08-08T10:27:57")

I used this in my code but something looks wrong:

    //create a java date formatter
    val SimpleDateFormat dateFormatter = new SimpleDateFormat( "YYYY-MM-dd HH:mm:ss" )

    //parse the date with java date formatter, and pass it to joda time DateTime constructor... 
    val DateTime origStartDate = new DateTime(dateFormatter.parse("2016-08-05 20:37:47"))

    logInfo("Logger","origStartDate: " + origStartDate) 

But something with the parse went wrong. It is not the correct date only time

2018-02-26 14:26:12.785 [INFO ] [clipse.smarthome.model.script.Logger] - origStartDate: 2016-01-04T20:37:47.000+01:100:

I’d start by fixing the year portion:

new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" )

@namraccr

perfect, this fixed the problem. Thanks a lot.

1 Like

I have two String values (one date “dateValue” and other for time “timeValue”),

I used your code and after some conversion it works :white_check_mark:

val SimpleDateFormat dateFormatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm" )        
val datetimeValue = dateValue + " " + timeValue
val String dateValue = dateFormatter.format(new Date(datetimeValue))                
val DateTime origStartDate = new DateTime(dateFormatter.parse(dateValue))

I tried using the following code, but it doesn’t work :x:

val SimpleDateFormat dateFormatter = new SimpleDateFormat( "yyyy-MM-dd HH:mm" )                
val DateTime origStartDate = new DateTime(dateFormatter.parse(dateValue + " " + timeValue))

Why second code doesn’t work ?