How can i format date in groovy script - groovy

Hi I have a date format that i am getting from my Jira Sprint Environment 2019-03-29T06:56:00.000-04:00
I am using groovy Script.
I have tried to use multiple format to make similar format like the above .
But Unable to do it.
Here are the below solution i have tried.
1 --
`def sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'")
sdf.setTimeZone(TimeZone.getTimeZone("GMT"))
log.debug("Printing Current time stamp date : "+sdf)
solution 1 is printing text only.
2 --
def now = new Date()
println now.format("yyyy-MM-dd'T'HH:mm:ss'Z'",TimeZone.getTimeZone('UTC'))
this one is printing
Printing Current time stamp date : Thu Sep 26 08:00:35 EDT 2019"
Can anyone help me on this?

So, the goal is to have date in format
2019-03-29T06:56:00.000-04:00
the following code does the formatting with timezone GMT-4
def now=new Date().format("yyyy-MM-dd'T'HH:mm:ss.SSSXXX",TimeZone.getTimeZone('GMT-4'))
println now
prints
2019-09-26T16:33:18.462-04:00
note that the variable now will contain String with formatted date
Check for all available date & time patterns:
https://docs.oracle.com/javase/8/docs/api/java/text/SimpleDateFormat.html

Given that you’ve got a Java 8 or newer underneath, all you need is
OffsetDateTime.now(ZoneId.systemDefault()).toString()
In my time zone (Europe/Copenhagen) I just got
2019-09-27T21:46:53.336204+02:00
If your default time zone is America/Montreal or America/New_York, you will get the time at offset -04:00 as long as summer time (Daylight Saving Time) is in effect, then -05:00.
And you can easily parse.
OffsetDateTime.parse( "2019-09-27T21:46:53.336204+02:00" )
See this code running at IdeOne.com.

def currentDate = new Date()
def date = currentDate.format('yyyy-MM-dd')
def time = currentDate.format('HH:mm:ss.SSS')
def dateTime = date.toString() + 'T' + time.toString() + 'Z'

Related

converting utc to est time in python

I have two dates, start date and end date, where both needs to used in google tag manager in EST timezone using python.
Currently when I fetch the dates from jira using api, I am getting in the UTC format for start date, but for end date, getting only the date value, that too in class str type.
This is what I got from jira
start date: 2021-09-20T07:16:08.000+0000
end date: 2021-09-21
Now I need to convert these and create a tag using python gtm api, where the start and end date should be in EST timezone.
Time in start date should be 00:00:00 and in end date, it should be 23:59:59 (both the time in EST).
Anyone please help me on this?
If im underderstanding correctly, it are both strings that you are getting back like this?
startdate = "start date: 2021-09-20T07:16:08.000+0000"
enddate = "end date: 2021-09-21"
Then first what you want to do, is split on the spaces and select the last item
justStartDatetimeString = startdate.split(" ")[-1]
justEndDatetimeString = enddate.split(" ")[-1]
If you just get the datetime as string like this, ignore part above:
"2021-09-20T07:16:08.000+0000"
Now just parse it towards a datetime by using the dateutil.parser
from datetime import datetime, time, timezone
import dateutil.parser
startdateDateTime = dateutil.parser.isoparse(justStartDatetimeString)
startdateDateTime = startdateDateTime.replace(tzinfo=timezone.utc).astimezone(tz=dateutil.tz.gettz('US/Eastern'))
startdateDateTime = startdateDateTime.replace(hour=0, minute=0, second=0)
For the enddate string
enddateDateTime = dateutil.parser.isoparse(justEndDatetimeString)
enddateDateTime = enddateDateTime.replace(tzinfo=dateutil.tz.gettz('US/Eastern'))astimezone(tz=dateutil.tz.gettz('US/Eastern'))
enddateDateTime = enddateDateTime.replace(hour=23, minute=59, second=59)

Unix millisecounds in date

im working on small project and i need to display date from api , api uses millisecounds and i cant really find a way to get date without time.
So far i didnt find anything usefull on internet.
Code i was using for this is:
ts= millisecounds im using
date = datetime.datetime.fromtimestamp(ts / 1000, tz=datetime.timezone.utc)
print(date)
But it prints something like 2010-10-10 10:10:10.100000+00:00
only thing i want from this is first part (2010-10-10)
how can i get date?
1. Naive Solution:
If you just want the date, you can try using the split method:
Code:
year_month_day = date.split(" ")[0]
print(year_month_day)
Output:
2010-10-10
2. Using strftime():
# using strftime
ts = 1588234567899 # Unix time in milliseconds
ts /= 1000 # Convert millisecondsto seconds
datetime_object = datetime.utcfromtimestamp(ts) # Create datetime object
date = datetime_object.strftime('%Y-%m-%d') # Strip just the date part out
print(date)
Output:
2020-04-30

How to add a day onto a date parsed string?

I am trying to do a simple add a day to my substring text that i've parsed into a date but it is not displaying correctly.
Below is the code:
def dateTimeDate = Date.parse("yyyy-mm-dd", textfromjson.substring(0,10)).format("yyyy-mm-dd")
def futureDateTimeDate = dateTimeDate + 1
When I do two logs for both defs, the original date and the future date which I want to be next day, I receive this output:
logs:
log.warn dateTimeDate
log.error futureDateTimeDate
output:
2018-02-23
2018-02-231
How can I get this to work so that it outputs: 2018-02-24 and not 2018-02-231
The answers posted already correctly point out that the date value needs to be incremented before it's formatted back into a String.
To this, I would like to add that if you're on Java 8 you can use its new Date/Time API as an alternative to java.util.Date, which can be problematic (even apart from mixing up 'm' and 'M' in format strings).
import java.time.*
def future = LocalDate.parse(textfromjson.substring(0,10)) + Period.ofDays(1)
You're parsing a String into a Date and then formatting it back into a String. Add to the Date object, not the String object.
def dateTimeDate = Date.parse("yyyy-mm-dd", textfromjson.substring(0,10))
def futureDateTimeDate = dateTimeDate + 1
log.warn dateTimeDate.format("yyyy-MM-dd")
log.error futureDateTimeDate.format("yyyy-MM-dd")
Also note that you probably want to be using MM (month in year) not mm (minute in hour).

How to get day from date using groovy

I want to get day (Ex Sun, Mon, Tue, ..) from date
def date = new Date()
def day = date[Calendar.DAY_OF_MONTH]
result is 18, but i want to get Mon.
And if I have 2017-10-09T00:00:00.000, I want to get day of 2017-10-09T00:00:00.000
Could you help me please?
The below code can help. It gets today's date first which is 18 Sep 2017 and then thats passed into calendar instance
Calendar instance then get the day in integer form i.e. monday=2, Then once we get the value 2 using map we say its Monday
def date = new Date()
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
def day = calendar.get(Calendar.DAY_OF_WEEK);
def map=[
1:"Sunday",
2:"Monday",
3:"Tuesday",
4:"Wednesday",
5:"Thursday",
6:"Friday",
7:"Saturday"]
log.info map[day]
Try Calendar.DAY_OF_WEEK. This returns an int which you can later map to the respective string.
Try using SimpleDateFormat, with EE format which tells days of week.
try below code :
def date = new Date()
SimpleDateFormat("EE").format(date) // EE means days of week
You can use this to output a three character representation of the name of the week day:
theDate = "2017-10-09T00:00:00.000";
def parsedDate = new Date().parse("yyyy-MM-dd'T'HH:mm:ss.SSS", theDate);
def day = new java.text.SimpleDateFormat("EEE", Locale.ENGLISH).format(parsedDate);
or for the full name use EEEE pattern.
Make sure to specify the Locale as this could differ per server configuration.

datetime.strptime with local time zone

I have in a dataframe a column time in UTC time, and I want to convert it in local time. I did this code:
from_zone = tz.tzutc()
to_zone = tz.tzlocal()
# utc = datetime.utcnow()
utc = datetime.strptime('2011-01-21 02:37:21', '%Y-%m-%d %H:%M:%S')
utc = utc.replace(tzinfo=from_zone)
# Convert time zone
central = utc.astimezone(to_zone)
Then I save it in a text file in a string.
So the string has this format:
2011-01-21 02:37:21+02:00
Then I load the text file in another program and I want to convert it in datetime format with local time zone
So I tried to use datetime.strptime() with the %Z parameter :
datetime.strptime(central,'%Y-%m-%d %H:%M:%S.%f Paris, Madrid')
Paris, Madrid is what the command datetime.tzname(central) gave me.
It is not working and I didn't find any explanations on how to use %Z.
If you have any explanations, please help me.
The datetime.strptime() function works a bit differently than this.
The first argument is the string with the time info, and the second argument is some type of formatting to it that allows the function to translate the string to a datetime object.
'.%f Paris, Madrid' is making the function think these words appear in the string, so an error will rise when the formatting and the string do not match.
The correct code would be:
datetime.strptime(central,'%Y-%m-%d %H:%M:%S%z')

Resources