The Now Platform® Washington DC release is live. Watch now!

Help
cancel
Showing results for 
Show  only  | Search instead for 
Did you mean: 

Format Date GlideDateTime to dd.mm.yyyy ?

Hendrik3
Kilo Contributor

I am running a server side script which calculates the last day of the month.

var gdt = new GlideDateTime();
gdt.addMonthsUTC(-1);
var month = gdt.getMonthUTC();
var year = gdt.getYearUTC();
var d = new Date(year, month + 1, 0);
gs.print(d); // last day of month

My current output looks as follows:

Wed Feb 28 2018 00:00:00 GMT-0800 (PST)

What I would love to receive is:
28.02.2018

I would love to avoid using stupid replace scripts or regex. There must be an easy way.

I have played with gdt.setDisplayValue  without success. 

Any help is upvoted

4 REPLIES 4

Lakshmaiah Dump
Giga Expert

Use following code.

var gdt = new GlideDate();
gdt.addMonthsUTC(-1);
gs.print(gdt.getByFormat("dd-MM-yyyy")); // last day of month

Tested with background scripts(Code)
find_real_file.png
Output:

find_real_file.png

Hit Correct, ️Helpful, or ❣️Like, Endorsers depending on the impact of the response 🙂
@Lakshmaiah Dumpala

Your format is fine, but how do I get the last date of the month using your script? I can't merge your part of code with mine somehow. 

I need the following ouput: 31.01.2018

Dubz
Mega Sage
Mega Sage

There's a lot of good stuff on this link that might help:

 

https://community.servicenow.com/community?id=community_blog&sys_id=bc0e6a2ddbd0dbc01dcaf3231f961931

 

Something like:

var newDate =   'Wed Feb 28 2018 00:00:00 GMT-0800 (PST)';     
var gdt = new GlideDate();     
gdt.setDisplayValue(newDate, "E MMMM dd yyyy");     
var dateTimeForField = gdt.getDisplayValue();   
gs.print(dateTimeForField); 

 

Jon Barnes
Kilo Sage

There are a few ways to do this calculation using GlideDate/GlideDateTime, but this is one I would do:

 

var gdt = new GlideDate();
gdt.addDaysUTC(gdt.getDaysInMonthUTC() - gdt.getDayOfMonthUTC());
gs.print(gdt.getByFormat('dd.MM.yyyy'));

 

You can also get the end of this month by calling gs.endOfThisMonth(). The downside of this approach is that you are stuck always getting this month's last day of month. the approach above will always get the last day of the month for whatever the GlideDate is. You can do those same calls above with GlideDateTime instead of GlideDate btw.

 

As a separate comment, I understand the need to convert the format to something specific, but my preference is to always show the user the dates/times in his/her preferred format (selected in their profile) instead of forcing them to view the date in a set format.