What might be wrong with this "insert date" macro?

NB this is LibreOffice Writer

What I did seemed very simple: recorded a macro by going Insert → Field → Date → chose format “YYYY-MM-DD”.

Then added text ": "

This is the code I see:

sub insert_date
rem ----------------------------------------------------------------------
rem define variables
dim document   as object
dim dispatcher as object
rem ----------------------------------------------------------------------
rem get access to the document
document   = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")

rem ----------------------------------------------------------------------
dim args1(5) as new com.sun.star.beans.PropertyValue
args1(0).Name = "Type"
args1(0).Value = 0
args1(1).Name = "SubType"
args1(1).Value = 0
args1(2).Name = "Name"
args1(2).Value = ""
args1(3).Name = "Content"
args1(3).Value = "0"
args1(4).Name = "Format"
args1(4).Value = 10084
args1(5).Name = "Separator"
args1(5).Value = " "

dispatcher.executeDispatch(document, ".uno:InsertField", "", 0, args1())

rem ----------------------------------------------------------------------
dim args2(0) as new com.sun.star.beans.PropertyValue
args2(0).Name = "Text"
args2(0).Value = ": "

dispatcher.executeDispatch(document, ".uno:InsertText", "", 0, args2())


end sub

But when I then run the macro, for today’s date 2017-02-17, for example, it gives

42783.7:

… although sometimes, in some documents it gives what it’s meant to give:

2017-02-17:

AFAICT, this may depend on the language of target paragraph. The “Format” is an index, and it may be absent for some languages.

Thanks very much. I just tried creating a new document… and (this is probably quite naive) tried explicitly setting the language. In fact I’m in UK and writing in English… but I set it to that (UK English) anyway.

It did the number thing.

Then I selected the number and tried to set the language (UK English) again… still stayed as a number. Bit puzzled…

Use this code to correctly set format (instead of put formatted strings to the cell):

sub SetDateFormat
    dim controller as object, oLocale as object
    controller = ThisComponent.CurrentController
    oLocale = controller.Selection.CharLocale

    dim nFmtId as Long
    nFmtId = ThisComponent.NumberFormats.queryKey("YYYY-MM-DD", oLocale, False)
    if nFmtId = -1 then
       nFmtId = ThisComponent.NumberFormats.addNew("YYYY-MM-DD", oLocale)
    end if

    controller.Selection.NumberFormat = nFmtId
end sub

Hallo

There is AFAIK no “hardcoded” relation between the choosen Numberformatcode YYYY-MM-DD and the recorded number 10084.

Sub insert_date
    cursor = thisComponent.CurrentController.ViewCursor
    cursor.String = format(now, "yyyy-mm-dd :")
    cursor.collapsetoEnd()
End Sub

Thanks, works perfectly.