Parse String to date, but result is different format - groovy

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)

Related

Add months to variable date in Groovy

I'm looking to calculate 6 months from a variable date. I have list of names and the date they last logged in. In groovy, how do I add 6 months to any given date?
the variable containing dates is lastloggedin. It is of date type and in format yyyy-MM-dd
import groovy.time.TimeCategory
use (TimeCategory) {
sixmonthsfromnow = lastloggedin + 6.month
}
Example result:
if lastloggedin = 2021-01-02, the result = "2021-01-026month"
You can parse the string into LocalDate
def someDate = LocalDate.parse('2021-01-02', 'yyyy-MM-dd')
Or if you have the Date type, you can convert it into LocalDate and then add months
date.toLocalDate() + 6.month
And then add months to it
someDate + 6.month
Or by using TimeCategory
def format = "yyyy-MM-dd"
def date = new Date()
def formattedDate = today.format(format)
use(TimeCategory) {
def oneYear = today + 6.month
}

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'

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

Resources