How to find the first day of Month

Mohit Yadav
Tera Expert

Hi Friends,

My Question is...

If a user is filling the date on the form in a date/time type field , how can i find the first day of that month which is filled by the user on the form.

e.g. - if user is filling 2015-10-4, then i want to get 2015-10-1. or if user is filling 2016-10-04, than i want to get 2016-10-1.

How can i achieve this in a Business Rule.

Thanks in Advance.

Regards,

Mohit Yadav

8 REPLIES 8

coryseering
ServiceNow Employee
ServiceNow Employee

Hi Mohit,



***Edited to fix multiple inaccuracies***



You want to get the GlideDateTime for the field in question, figure out what day number they picked, and subtract n-1 days from that to get the first day of that month.



So here is an example (I'm not currently logged in to any instances, so I can't test this code- you may have to change it to fix bugs or syntax errors).



function onBefore(current, previous) {


      var sentDateTime = current.u_date_field.getGlideObject();


      var sentDay = sentDayTime.getDayOfMonth(); //example: if they picked May 04, this would be 4


   


      var firstOfMonth = new GlideDateTime(sentDateTime);


      firstOfMonth.addDaysLocalTime(1 - sentDay);



      gs.log(firstOfMonth.getDisplayValue()); //example: if they picked May 04, this should be 2015-05-01 or whatever your date display format is


}



So that's the gist. You could simplify it a bit, but I think that would work. I am not too clear on the difference between addDaysLocalTime and addDaysUTC so try both in various circumstances and see which one is right for your case.


Hi Cory,



I tried this but in log (gs.log(firstOfMonth.getDisplayValue())) , it is giving May 04, not 2015-05-01 00:00:00.



And when i try to print (firstOfMonth.subtractDays(sentDay - 1)); , it is giving undefined.



Thanks & Regards,


Mohit Yadav


Hi Mohit,



I believe the problem is that subtractDays is not defined in the GlideDateTime. Use addDays with a negative number instead.



Thanks,


Berny


He goes an example, using Cory's code as a baseline and also fixing a small typo in line 04.



Feel free to run it from a background script to test it out:



var sentDateTime = new GlideDateTime();


var daysInMonth = sentDateTime.getDaysInMonth();


var sentDay = sentDateTime.getDayOfMonth();


var firstOfMonth = new GlideDateTime(sentDateTime);  


firstOfMonth.addDays( -1 * (sentDay-1));  


 


gs.print(firstOfMonth.getDisplayValue());



Output:


*** Script: 2015-10-01 23:47:06



Thanks,


Berny