Date formatting in Karate - karate

I have the the below date returned from the SQL query in Karate feature file:
2020-01-31 00:00:00.0
I need to convert it to: 31-JAN-20 format. I have tried the below:
* def effectiveDt =
"""
function(s) {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat("dd-mon-yy");
return return sdf.format(s)
}
"""
but its not working for me.
but the below worked and returns 31-00-19, but I want 31-JAN-20 format
var sdf = new SimpleDateFormat("dd-mm-yy");
Any help would be appreciated!

Here is an example that worked for me:
* def getSubtractedYear =
"""
function(s) {
var DateTimeFormatter = Java.type("java.time.format.DateTimeFormatter");
var LocalDate = Java.type("java.time.LocalDate");
var ChronoUnit = Java.type("java.time.temporal.ChronoUnit");
var dtf = DateTimeFormatter.ofPattern("MM/dd/yyyy");
try {
var adj = LocalDate.parse('02/02/2020', dtf).minusMonths(12);
return dtf.format(adj);
} catch(e) {
karate.log('*** date parse error: ', s);
}
}
"""
And call like:
* string subtracted = call getSubtractedYear aDate

Related

How do I extract current date, month and year in the format yyyy-mm-dd in karate dsl?

* def date =
"""
function(s) {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
return sdf.parse(s).time;
}
"""
Currently, I'm using this. Any help is much appreciated.
You can also archive the following by using javascript as follows:
* def todaysDate =
"""
function()
{
var d=new Date();
var month = String(d.getMonth() + 1);
var day = String(d.getDate());
var year = String(d.getFullYear());
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return year+'/'+month+'/'+day
}
"""
* print todaysDate()
Here you go:
* def today =
"""
function() {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat('yyyy-MM-dd');
return sdf.format(new java.util.Date());
}
"""
* print today()

Got wrong date when converting string date retrieved from the api

I'm calling an API to get some dates, but the API returns the date in string format so I'm using new Date() to convert it to date format, the problem is that after the conversion I'm getting a wrong date
For example new Date("2019-04-19") is returning Thu Apr 18 19:00:00 GMT-05:00 2019
this is my code
function HebrewCalAPI(fechas)
{
var response = UrlFetchApp.fetch("https://www.hebcal.com/hebcal/?v=1&cfg=json&maj=on&min=on&mod=on&nx=on&year=now&month=x&ss=on&mf=on&c=on&geo=geoname&geonameid=3530597&m=50&s=on");
var data = JSON.parse(response.getContentText());
var arrayEmpiezan = []
for(var i in fechas)
{
for(var i2 in data.items)
{
if(data.items[i2].title == fechas[i])
{
arrayEmpiezan.push(new Date(data.items[i2].date));
}
}
}
return arrayEmpiezan
}
var fiestasEmpiezan = ["Erev Pesach","Pesach VI (CH''M)","Erev Shavuot","Erev Rosh Hashana","Erev Yom Kippur","Erev Sukkot","Sukkot VII (Hoshana Raba)"]
var fiestasAcaban = ["Pesach II", "Pesach VIII","Shavuot II","Rosh Hashana II","Yom Kippur","Sukkot II","Simchat Torah"]
var FiestaEmpieza = date
var FiestaAcaba = date
FiestaEmpieza = HebrewCalAPI(fiestasEmpiezan)
FiestaAcaba = HebrewCalAPI(fiestasAcaban)
Any help please ?

Karate: match with parametrized regex

I didn't find the right way to write a match with regexp cointaining a variable:
* def getYear =
"""
function() {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat('yyyy');
var date = new java.util.Date();
return sdf.format(date);
}
"""
* def currentYear = getYear()
* def testmatch = { gencode: '#("000" + currentYear + "0000012345")' }
* match testmatch == { gencode: '#regex "[0-9]{3}" + currentYear + "[0-9]{10}"' }
There is a way to do this?
Thanks,
Lorenzo
First, normally when you are doing matches like this, regex is un-necessary, because you might as well do an exact match.
But anyway this is the solution, refer: https://github.com/intuit/karate#self-validation-expressions
* def isValidYear = function(x){ return new RegExp("[0-9]{3}" + currentYear + "[0-9]{10}").test(x) }
* assert isValidYear('00020190000012345')
* match testmatch == { gencode: '#? isValidYear(_)' }

Binary operator '-' cannot be applied to two (NSDate?) operators

Trying to get a total amount of time from a start time and end time.
I have the DateFormatter correct as in Extension.swift below but I am getting confused on the way to calculate bottomtime - starttime.
Any help is appreciated. Thanks
Extension.swift
extension NSDate{
var bottomtimestringValue: String{
return self.toString()
}
func tobottomtimeString() -> String {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
let str = formatter.stringFromDate(self)
return str
}
}
extension String{
var bottomtimedateValue: NSDate?{
return self.toDate()
}
func tobottomtimeDate() -> NSDate? {
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
if let date = formatter.dateFromString(self) {
return date
}else{
// if format failed, Put some code here
return nil // an example
}
}
}
Adddivelogviewcontroller.swift
var a = (textFieldStartTime.text.starttimedateValue)
var b = (textFieldEndTime.text.endtimedateValue)
var sum = b - a
textFieldBottomTime.text = "\(sum)"
That's correct-- the - operator is not defined for NSDate?, so you can't find the difference that way. Since a and b are both NSDate?, you could find the difference like this:
if let dateA = a, dateB = b {
let difference = dateA.timeIntervalSinceReferenceDate - dateB.timeIntervalSinceReferenceDate
}
Here, difference's type will be NSTimeInterval?.
Or if you prefer, you could add a definition of - for NSDate?, which might look like this:
func -(lhs:NSDate?, rhs:NSDate?) -> NSTimeInterval? {
if let left=lhs, right=rhs {
return left.timeIntervalSinceReferenceDate - right.timeIntervalSinceReferenceDate
} else {
return nil
}
}
Add that and you can use - above.
OK, not really sure if thats working or not but i get no errors. What I need this to do calculate after the end time picker OK botton is pressed
func OK3ButtonTapped(sender: UIBarButtonItem) {
self.textFieldEndTime.endEditing(true)
self.textFieldEndTime.text = endtimePickerView.date.endtimestringValue
var a = (textFieldStartTime.text.starttimedateValue)
var b = (textFieldEndTime.text.endtimedateValue)
var difference: String = ""
if let dateA = a, dateB = b {
let difference = dateA.timeIntervalSinceReferenceDate - dateB.timeIntervalSinceReferenceDate
}
textFieldBottomTime.text = "\(difference)"
}

convert date from json format to other formats in sencha

Can anyone tell me how to convert date from Json data to normal date format in sencha.
var df = this.dateFormat;
if (!v) {
return v;
}
if (Ext.isDate(v)) {
return v;
}
if (df) {
if (df == 'timestamp') {
return new Date(v * 1000);
}
if (df == 'time') {
return new Date(parseInt(v, 10));
}
return Date.parseDate(v, df);
}
var parsed = Date.parse(v);
return parsed ? new Date(parsed) : null;
Thanks in advance
The Ext.Date class is what you're looking for. Try something like:
var parsed = Ext.Date.parse(valueFromJSON, "Y-m-d g:i:s A");
The Ext.Date.parse method returns a Date.