How convert input String to Integer groovy - groovy

I have a String and I need to sum, but I don't know how!
How I can convert String Input like this:
01:20
to Integer for use in sum of hour and minutes?

Assuming you've got your string defined in variable:
String timeStr = '01:00'
The shortest way I can think of would look like:
timeStr[0..1].toInteger()
Just to clarify, the above line is equivalent of:
timeStr.substring(0, 2).toInteger()
Please note the difference between specifying 'to' index.
With Groovy range it's inclusive.

You can parse that into a Date using:
Date.parse( 'HH:mm', '01:00' )
If you need something to add on to a Date at a later time, you can do:
import groovy.time.*
String time = '01:00'
def duration = use( TimeCategory ) {
Date.parse( 'HH:mm', time ) - Date.parse( 'HH:mm', '00:00' )
}
Then, later on:
use( TimeCategory ) {
println new Date() + duration
}

def hours = Date.parse("HH:mm", str).getHours();

Related

how to increment date by 1. input is string type having date as a value

I have to develop a custom groovy code to take string as input, it would be a date. Increase the date by one, then return it. As the input is a string I would need help to handle this.
thanks in advance for the help.
for example.
Input to the script - 05/12/2021
Output - 06/12/2021
This is the Groovy way to do it:
def input = '05/12/2021'
def today = Date.parse('dd/MM/yyyy', input)
def tomorrow = today.plus(1)
assert tomorrow.format('dd/MM/yyyy') == '06/12/2021'
You can do all of that in one line too:
Date.parse('dd/MM/yyyy', '05/12/2021').plus(1).format('dd/MM/yyyy')

I'm trying to convert 2019-11-22 11:29:34.56 to epoch timestamp in seconds +1minute in SoapUI groovy

What I want is to take current date and put it to the variable in my test case as something like that 1562239260 using this timestamp converter:
https://www.timestampconvert.com/?go1=true&m=07&d=04&y=2019&hours=13&min=21&sec=000&Submit=++++++Convert+to+timestamp+++++&offset=-1
I tried to put this code as a property value ${=def now=new Date();now.format("yyyy-MM-dd")} but the format is wrong.
Ok partially I solved the problem ${=def now=new Date();epoch_milis = now.getTime()}
but i need this time stamp to be ahead for 1minute
Here it is in pure Groovy:
String myTime = '2019-07-04 13:21:00'
Date myTimeParsed = Date.parse('yyyy-MM-dd HH:mm:ss', myTime)
assert myTimeParsed.getTime()/1000 == 1562239260
long epochTime = (myTimeParsed.getTime()/1000) + 60
import java.time.Instant
import java.util.Date
import java.text.SimpleDateFormat
Date sixtyLater = Date.from(Instant.ofEpochSecond(epochTime))
assert new SimpleDateFormat('yyyy-MM-dd HH:mm:ss').format(sixtyLater) == '2019-07-04 13:22:00'
this is the correct answer
${=def now=new Date();epoch_milis = now.getTime()+120000}
I am ahead of 2 minutes :D

Convert date string to timestamp, groovy

I have a date string as follows:
201805041235040000000
Which I would like to convert to timestamp with zone in Groovy.
Tried this:
def timestamp = Date.parse("yyyyMMddHHmmss", timstamp).format("yyyy-MM-dd'T'HH:mm:ssZ");
But failed, got error:
No signature of method: static java.util.Date.parse() is applicable for argument types.
Let me know where am I going wrong.
Try this:
String t2,st = "16/08/2007 09:04:34"
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss")
Date date = sdf.parse(st)
Timestamp timestamp = new Timestamp(date.getTime())
t2 = timestamp.toString()
Hope it helps....
This works...
String input = '201805041235040000000'
String timestamp = Date.parse('yyyyMMddHHmmss', input).format("yyyy-MM-dd'T'HH:mm:ssZ")
It is a bit unclear what you are looking for. If you just need a time stamp from parsing your date string, you can use the groovy extension Date.toTimestamp():
def ts = Date.parse("yyyyMMddHHmmssSSS", "201805041235040000000".take(17)).toTimestamp()
where the take(17) is there to discard any trailing zeros not included in the date pattern yyyyMMddHHmmssSSS. I made the assumption that three of the tailing zeros were milliseconds. If that's not the case:
def ts = Date.parse("yyyyMMddHHmmss", "201805041235040000000".take(14)).toTimestamp()
what is unclear is what you mean when you say "with zone". So assuming you just want to include the current time zone information and generate a String, I don't see a reason why you should convert from date to timestamp in the first place (Timestamp after all is a Date as it inherits from Date). If you just need the timezone spelled out you can do:
def withZone = Date.parse("yyyyMMddHHmmss", "201805041235040000000".take(14)).format("yyyy-MM-dd'T'HH:mm:ssZ")
println withZone
which on my machine where I'm sitting in Sweden prints out:
~> groovy withTimeZone.groovy
2018-05-04T12:35:04+0200
timestamp must be string. Try this:
Date.parse("yyyyMMddHHmmss", timstamp?.toString()[0..13])
.format("yyyy-MM-dd'T'HH:mm:ssZ")

How to get the trimmed value 88 out of 0.0.88 in groovy

I am trying to get the value 88 out of 0.0.88 using groovy. Is there any easy way to get that.
Use tokenize() instead of split()
assert "0.0.88".tokenize('.')[2] == '88'
Based on your comments, it looks like you are trying to get seconds from a date.
Here is one approach:
String theDate = "28/09/2010 16:02:43";
def newdate = new Date().parse("d/M/yyyy H:m:s", theDate)
log.info newdate.getSeconds()
Or if you just have the time part of the date, the following works too:-
String theDate = "16:02:43";
def newdate = new Date().parse("H:m:s", theDate)
log.info newdate.getSeconds()
The actual problem is likely more nuanced than stated, but taken at its face value, I'd just do:
assert '0.0.88' - '0.0.' == '88'

Passing parameters to strftime method

I'm new to python. my question is how to pass parameter to date.strftime() or a workaround
Below is the code
from datetime import date
dl_date = date.today()
p = '%d%b%Y' # the format may vary %d%B%Y or %d%m%Y or % d%M%Y etc
file_date_format = "{0}/{1}/{2}".format(str(dl_date.strftime('%r')),str(dl_date.strftime('%r').upper())
, str(dl_date.strftime('%r'))) % (p[:2], p[2:4], p[4:6])
print(file_date_format)
Help is much appreciated.
No need to use percent style string formatting here. Just stick the p slices directly in the strftime calls.
from datetime import date
dl_date = date.today()
p = '%d%b%Y' # the format may vary %d%B%Y or %d%m%Y or % d%M%Y etc
file_date_format = "{0}/{1}/{2}".format(
str(dl_date.strftime(p[:2])),
str(dl_date.strftime(p[2:4]).upper()),
str(dl_date.strftime(p[4:6]))
)
print(file_date_format)
Result:
14/NOV/2014

Resources