How to get only first part of the date ('DD') from an entire date? - servicenow

I've converted a date into string. Now, I want to parse a string to get the DD part from DD-MM-YYYY.
For e.g.
If the date is 03-05-2017 (DD-MM-YYYY) then the goal is to get only first part of the string i.e. 03 (DD).

You've tagged this question as a ServiceNow question, so I assume you're using the ServiceNow GlideDateTime Class to derive the date as a string. If that is correct, did you know that you can actually derive the day of the month directly from the GlideDateTime object? You can use the getDayOfMonth(), getDayOfMonthLocalTime(), or getDayOfMonthUTC().
You could of course, also use String.prototype.indxOf() to get the first hyphen's location, and then return everything up to that location using String.prototype.slice().
Or, if you're certain that the day of the month in the string will contain an initial zero, you can simply .slice() out a new string from index 0 through index 2.
var date = '03-05-2017';
var newDate = date.slice(0, 2);
console.log(newDate); //==>Prints "03".
var alternateNewDate = date.slice(0, date.indexOf('-'));
console.log(alternateNewDate); //==>Prints "03".

Related

How to insert previous month of data into database Nifi?

I have data in which i need to compare month of data if it is previous month then it should be insert otherwise not.
Example:
23.12.2016 12:02:23,Koji,24
22.01.2016 01:21:22,Mahi,24
Now i need to get first column of data (23.12.2016 12:02:23) and then get month (12) on it.
Compared that with before of current month like.,
If current month is 'JAN_2017',then get before of 'JAN_2017' it should be 'Dec_2016'
For First row,
compare this 'Dec_2016'[month before] with month of data 'Dec_2016' [23.12.2016].
It matched then insert into database.
EDIT 1:
i have already tried with your suggestions.
"UpdateAttribute to add a new attribute with the previous month value, and then RouteOnAttribute to determine if the flowfile should be inserted "
i have used below expression language in RouteOnAttribute,
${literal('Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'):getDelimitedField(${csv.1:toDate('dd.MM.yyyy hh:mm:ss'):format('MM')}):equals(${literal('Dec,Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov'):getDelimitedField(${now():toDate(' Z MM dd HH:mm:ss.SSS yyyy'):format('MM'):toNumber()})})}
it could be failed in below data.,
23.12.2015,Andy,21
23.12.2017,Present,32
My data may contains some past years and future years
It matches with my expression it also inserted.
I need to check month with year in data.
How can i check it?
The easiest answer is to use the ExecuteScript processor with simple date logic (this will allow you to use the Groovy/Java date framework to correctly handle things like leap years, time zones, etc.).
If you really don't want to do that, you could probably use a regex and Expression Language in UpdateAttribute to add a new attribute with the previous month value, and then RouteOnAttribute to determine if the flowfile should be inserted into the database.
Here's a simple Groovy test demonstrating the logic. You'll need to add the code to process the session, flowfile, etc.
#Test
public void textScriptShouldFindPreviousMonth() throws Exception {
// Arrange
def input = ["23.12.2016 12:02:23,Koji,24", "22.01.2016 01:21:22,Mahi,24"]
def EXPECTED = ["NOV_2016", "DEC_2015"]
// Act
input.eachWithIndex { String data, int i ->
Calendar calendar = Date.parse("dd.MM.yyyy", data.tokenize(" ")[0]).toCalendar()
calendar.add(Calendar.MONTH, -1)
String result = calendar.format("MMM_yyyy").toUpperCase()
// Assert
assert result == EXPECTED[i]
}
}

Lotus sorting view on orderdate does not work properly

I have created a view in which I also have a column which holds dates. This column can be sorted on ascending and descending. This is my column properties value:
But the problem is that the view does not sort the dates properly:
And here a screenshot of the orderdate field itself:
And here screenshot of the document with the orderdate that is out of order in the view:
Update
Some documents had the orderdate as text instead of date.. I create these documents through a java agent. The field orderdate I fill in like this:
SimpleDateFormat formatterDatumForField=new SimpleDateFormat("dd-MM-yyyy");
docOrder.replaceItemValue("Orderdatum",formatterDatumForField.format(currentDateForField));
But it is saved as text instead of date. Anyone knows why?
Problem was that orderdate field was set by a backend agent and this field was set with a string.
I know saved the current time as a DateTime object and now it works:
DateTime timenow = session.createDateTime("Today");
timenow.setNow();
docOrder.replaceItemValue("Orderdatum", timenow);
It's not clear to me why it's not working for you, but you can brute force it with something like this in the column formula
dateForSure := #TextToTime(OrderDatum);
#Text(#Year(dateForSure)) + "-" + #Text(#Month(dateForSure)) + "-" + #Text(#Day(dateForSure));
Also: your Java code saves a text value because the format() method of SimpleDateFormat returns a StringBuffer. The ReplaceItemValue method generates a text item when its input is a String or StringBuffer. Assuming your form defines OrderDatum as a Time/Date field, you can call Document.ComputeWithForm in your code to force it to convert the text item to a Time/Date. Another method - probably preferable given the potential side-effects of calling ComputeWithForm would be to create a DateTime object in your Java code and pass it to the ReplaceItemValue method instead.
It's because formatterDatumForField.format(currentDateForField) returns a String instead of a date/time value. Assuming that currentDateForField is a date/time value, you should change
SimpleDateFormat formatterDatumForField=new SimpleDateFormat("dd-MM-yyyy");
docOrder.replaceItemValue("Orderdatum",formatterDatumForField.format(currentDateForField));
to
docOrder.replaceItemValue("Orderdatum",currentDateForField);

Why date validation in Google sheets rejects today's date before 8:00am?

I've created a Google sheet to keep a list of work tasks with a column to track the date on which items are created, and built a script to automatically populate the cells in that column with the day's date when a new line is inserted.
The cell (e.g. G9) that is target of the script uses the following validation formula to make sure that when users change the date, they use a date that is neither a weekend nor in the future:
=and(isdate(G9), weekday(G9,2)<6, G9<=today())
IT ONLY WORKS BUT ONLY IF THE SCRIPT IS RUN ANYTIME AFTER 8:00am ! If I try using it any earlier the cell validation will reject the input!
The script looks like this (curRow is the number of the row that's been added):
// Adds today's date without using =today()
var myrangename = "G"+curRow;
var dateCell = sheet.getRange(myrangename);
var d = new Date();
var dateArr = [];
dateArr[0]=d.getFullYear();
dateArr[1]=d.getMonth() + 1; //Months are zero based
dateArr[2]=d.getDate();
dateCell.setValue(dateArr.join('/'));
(n.b.: I cannot use the script to simply put =today() in the cell because all the entries would change every day. )
WHY DOES IT ONLY WORK AFTER 8:00AM? Is Google somehow running on a different time zone than my computer?? I'm based in the UK, so using BST, but that shouldn't be a problem, shouldn't it...?
Try
var d = new Date();
var d = Utilities.formatDate(d, "GMT+1", "yyyy-MM-dd HH:mm:ss");
I am not sure if google would recognise BST as a time zone, but you could also try
var d = Utilities.formatDate(d, "BST", "yyyy-MM-dd HH:mm:ss");
Thank you for your suggestion, Aprillion. Turns out that a Google Sheets file has its own internal time-zone setting! which in my case was set to American Pacific time (so 8hrs behind)
(You'd think it would pick up the date and time info automatically from Windows, like other applications do!)
To set the sheet's time-zone to the correct one, you need to go to the main menu, click 'File', then 'Spreadsheet settings...', and adjust as necessary.
The script and validation now all work fine.
Thank you all for your help.

What does this d3 time format function mean?

I know there is a specified d3 time formatting. But when I check the example shown here d.Year = new Date(d.Year,0,1); the year's format is "1996"
Does it one of the other ways to format year as a string here, i don't quite understand it.
Also, if my time format is like"01/01/96", what is the right format to get the string here?
This isn't a d3 date formatting function. Its one of the basic forms of the Javascript Date constructor.
Specifically, it is using the multi-parameter form of the constructor:
new Date(year, month, day, hour, minute, second, millisecond);
except that all the time parameters are left as their default (0/midnight) values. If the original value for d.Year is the string "1996", the line
d.Year = new Date(d.Year,0,1);
creates a new Date object with year 1996 (the conversion from string to number will be automatic), month value zero (January), day value 1, and time midnight.

D3js getting just a part of a value and converting it to decimal

I'm trying to get a decimal value for a value that is expressed in a date. My problem is that I need only the time in the date, not the actual date itself. So here part of my .json data:
var data = [
{
"Id":"1390794254991",
"Tz":"Europe/Amsterdam",
"From":"27. 01. 2014 4:44",
"To":"27. 01. 2014 12:09",
"Sched":"08. 02. 2014 5:24",
"Hours":"7.430"
}]
So basically i would like to take the "From" value and get just the time returned in a decimal value. I don't think converting the time to a decimal number with Time Formatting, it's just the splitting of a value that seems pretty hard to me. Any of you guys have a clue how this could be achieved?
Thanks,
Cas
Edit: Okay, here we go. I made a JSFiddle to clear things up. Because there is a TIME (HH:MM) in my date, the rectangles in my barchart don't come on a specific day in the xAxis. INSTEAD they come out on a day AND time on the xAxis.
I just need it to be the specific date, not the date AND time.
I think I have to change something in the following part:
dataFiltered.forEach(function(d) {
d.From = parseDate(d.From);
});
Just don't really see what...
With d3, you'd construct a time parser, give it a string to parse, and get back a Date object.
var parser = d3.time.format('%d. %m. %Y %H:%M');
var date = parser.parse("05. 52. 2014 4:32");
Then you can do as you wish with this date object, including
var hours = date.getHours() // 4
var minutes = date.getMinutes() // 32
But, did you mean you don't want to use d3 (despite your question being tagged with d3)? If so, you can also use RegExp:
var dateString = "05. 52. 2014 4:32";
var matches = dateString.match(/(\d?\d):(\d\d)$/);
// yields ["4:32", "4", "32"]
Then you can get the tokens you want either via
var hours = matches[1];
var minutes = matches[2]
or
var hours = RegExp.$1;
var minutes = RegExp.$2
In either case though, RegExp gives you back strings, so you need to convert them to Numbers if you're doing quantitative stuff with them:
var hours = parseInt(matches[1]);
or more cryptically
var hours = +matches[1];

Resources