How to get the first of the month of a specific date?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-02-2016 08:34 PM
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?
- Labels:
-
Scripting and Coding
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-02-2016 09:27 PM
Try the following:
var newTime = new GlideDateTime(source.u_start_time);
answer = newTime.setDayOfMonthUTC(1);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-02-2016 11:18 PM
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());
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-03-2016 06:07 AM
Thank you for this answer!!!!!!!!!!!!!! it worked :D:D
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-03-2016 07:43 AM
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;