How to convert (and format) a DateTime item in a rule

I have a DateTime item:

DateTime Weather_Forecast_Day_1 "[%1$tA]" <clock> (Weather) { weather="locationId=home, forecast=1, type=condition, property=observationTime" }

The idea of this is to tell me what tomorrow is called (i.e. Tuesday).

Now I want to send this date as a string over MQTT, but I’ve no idea how to:

a) convert it to string
b) format it

I’ve tried this:

WeatherMQTT_1.postUpdate(Weather_Forecast_Day_1.toString("HH:mm"))

I’ve also tried this:

WeatherMQTT_1.postUpdate(String::format( "%1$td %1$tb %1$tl:%1$tM %1$tp", Weather_Forecast_Day_1.state))

Basically, neither work. I managed to get the .toString not to error on the console, however it didn’t format correctly, and also it removed everything that I added onto the MQTT message after that (when I used the + operator to add more text).

Any ideas?

Hi Mat

Try something like this:

var String day = Weather_Forecast_Day_1.state.format("%1$tA")
WeatherMQTT_1.postUpdate(day)

Hopefully that should work, I quickly tested it in my setup with the following:

rule "test"
when 
    Item test_switch changed to ON
then
    dateTime.postUpdate(new DateTimeType())
end

rule "test"
when
    Item dateTime received update
then
    var String tmp = dateTime.state.format("%1$tA")
    logInfo("dateTime",tmp)
end

With it having passed midnight for us Brits, my version printed out “Tuesday”.

Daniel, thanks - that worked a treat. (I had to double-take, hadn’t realised it was quite so late here!)

Hi, quick follow-up question.

My rule has this:

var String DateTimeStampInitial = String::format( "%1$td %1$tb %1$tl:%1$tM %1$tp", new Date() )

It works, and provides date in this format: 27 Jan 10:17 pm

Can’t remember how I knew how to format it in this way, but can someone tell me where the “reference” for date time formatting is?

e.g. how come the %1$tb formats to give “Jan”?

I’ve looked in the Joda DateTimeFormat manual, but nowhere can I find the b formatting operator!

Hi Mat, try here:

https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html

which specifies

'b' Locale-specific abbreviated month name, e.g. "Jan", "Feb".

2 Likes

Thanks so much!

This page has comprehensive solutions : DateTime Conversion (openHAB 3.x)