How to get day from date using groovy - 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.

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)

How to get 1st calendar day of the current and next month based on a current date variable

I have a date variable calls today_date as below. I need to get the 1st calendar day of the current and next month.
In my case, today_date is 4/17/2021, I need to create two more variables calls first_day_current which should be 4/1/2021, and first_day_next which should be 5/1/2021.
Any suggestions are greatly appreciated
import datetime as dt
today_date
'2021-04-17'
Getting just the first date of a month is quite simple - since it equals 1 all the time. You can even do this without needing the datetime module to simplify calculations for you, if today_date is always a string "Year-Month-Day" (or any consistent format - parse it accordingly)
today_date = '2021-04-17'
y, m, d = today_date.split('-')
first_day_current = f"{y}-{m}-01"
y, m = int(y), int(m)
first_day_next = f"{y+(m==12)}-{m%12+1}-01"
If you want to use datetime.date(), then you'll anyway have to convert the string to (year, month, date) ints to give as arguments (or do today_date = datetime.date.today().
Then .replace(day=1) to get first_day_current.
datetime.timedelta can't add months (only upto weeks), so you'll need to use other libraries for this. But it's more imports and calculations to do the same thing in effect.
I found out pd.offsets could accomplish this task as below -
import datetime as dt
import pandas as pd
today_date #'2021-04-17' this is a variable that is being created in the program
first_day_current = today_date.replace(day=1) # this will be 2021-04-01
next_month = first_day_current + pd.offsets.MonthBegin(n=1)
first_day_next = next_month.strftime('%Y-%m-%d') # this will be 2021-05-01

How can i format date in groovy script

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'

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).

Parse String to date, but result is different format

I have been trying to parse a string into dates, but after parsing, the format changes. I have this in my controller:
def dates = params.id
def dates2 = new Date().parse("yyyyy:MM:dd", dates)
System.out.println(dates2)
But the result is Tue Oct 23 00:00:00 CST 2012 instead of the the format that I added. How can I force it to that format yyyy:MM:dd?
That's just the String representation of a Java Date
If you use Date.format to print it out, you'll see the format you want:
def dates = params.id
// parse is static, no need for new
def dates2 = Date.parse( 'yyyy:MM:dd', dates )
println( dates2.format( 'yyyy:MM:dd' ) )
(I also assume you mean yyyy, not 5 ys)

Resources