Scripting help- getting the date in yyyy-mm-dd format

chidanandadhath
Kilo Guru

I have the below script where I'm getting first and last date of the month but not in yyyy-mm-dd format, 

var nowDateTime = new GlideDateTime('2019-05-10');
var date = nowDateTime.getDate();
var month = date.toString().split("-")[1];
var year = date.toString().split("-")[0];
var FirstDay = new Date(year, month-1, 1);
var LastDay = new Date(year, month, 0);
gs.info(FirstDay);
gs.info(LastDay);

 

Output:

*** Script: Wed May 01 2019 00:00:00 GMT-0700 (PDT)
*** Script: Fri May 31 2019 00:00:00 GMT-0700 (PDT)
1 ACCEPTED SOLUTION

Nirosha Uddandi
Kilo Guru

hi ,try with below code

var nowDateTime = new GlideDateTime('2019-05-10');
var date = nowDateTime.getDate();
var month = date.toString().split("-")[1];
var year = date.toString().split("-")[0];
var FirstDay = new Date(year, month-1, 1);
var LastDay = new Date(year, month, 0);
var first= new GlideDateTime(FirstDay);
var last = new GlideDateTime(LastDay);
gs.info(first);
gs.info(last);

View solution in original post

7 REPLIES 7

The SN Nerd
Giga Sage
Giga Sage

Please follow my blog here (Secrets of GlideDateTime) which outlines how to format date and times in any format.


ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

Hi Paul, 

I modified the script as below

var nowDateTime = new GlideDateTime('2019-05-10');
var date = nowDateTime.getDate();
var month = date.toString().split("-")[1];
var year = date.toString().split("-")[0];
var FirstDay = new Date(year, month-1, 1);
var LastDay = new Date(year, month, 0);
gs.info(FirstDay);
gs.info(LastDay);

var newDate = FirstDay;
var gdt = new GlideDateTime();
gdt.setDisplayValue(newDate, "E, MMMM dd, yyyy K:mm a");
var dateTimeForField = gdt.getDisplayValue();
gs.print(dateTimeForField);

 

but I'm getting error as below

Evaluator: java.lang.RuntimeException: Unparseable date: "Wed May 01 2019 00:00:00 GMT-0700 (PDT)"

The SN Nerd
Giga Sage
Giga Sage

Also, GlideDate has the following methods:

getMonth ()

getYear ()

getDay()


ServiceNow Nerd
ServiceNow Developer MVP 2020-2022
ServiceNow Community MVP 2019-2022

I want to get first day and last day by passing date of the month, which I'm getting but not in required format