How to get the first of the month of a specific date?

zsquared
Tera Contributor

Hello,

I am trying to round each date (u_start_time) to the first of the month.   I have tried using the gs.beginningOfThisMonth() but that doesn't seem to work.

//

var startTime = source.u_start_time;

var newTime = new GlideDateTime(startTime);

answer = gs.beginningOfThisMonth(startTime);

Any ideas?

4 REPLIES 4

Jim Coyne
Kilo Patron

Try the following:



var newTime = new GlideDateTime(source.u_start_time);


answer = newTime.setDayOfMonthUTC(1);


tanumoy
Tera Guru

Here you go:



var sentDateTime = new GlideDateTime(source.u_start_time);


var daysInMonth = sentDateTime.getDaysInMonth();


var sentDay = sentDateTime.getDayOfMonth();


var firstOfMonth = new GlideDateTime(sentDateTime);


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



gs.print(firstOfMonth.getDisplayValue());


zsquared
Tera Contributor

Thank you for this answer!!!!!!!!!!!!!! it worked :D:D


zsquared
Tera Contributor

So I realized that if the month comes in as the first of the month, this script actually rounds the month to first of the previous month.   I tried to add an if condition stating that if it's already the first of the month to not change the date but for some reason the if condition is not running correctly:


//get the source start date


var sentDateTime = new GlideDateTime(source.u_start_time);




//get the number of days in the start date's month


var daysInMonth = sentDateTime.getDaysInMonth();




//get the day of the month of the start date


var sentDay = sentDateTime.getDayOfMonth();




//if sentDay is the first, use original source date as the date


var inputDate = source.u_start_time;




if (sentDay <= 1) {


  inputDate = source.u_start_time;


} else {


  //else convert it to the first of the month


  var firstOfMonth = new GlideDateTime(sentDateTime);


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


  inputDate = firstOfMonth.getDisplayValue();


}



answer = inputDate;