Groovy joda-time convert time - grails

In my domain I have
Time startTime
Time endTime
In my controller I need to covert the time from the view which is in a format of HH:MM to the acceptable format to submit to the domain. I have installed the plugin Joda-Time but I've come a bit stuck.
def startTime = params.startTime
def fmt_in = DateTimeFormat.forPattern("HH:mm:ss")
def fmt_out = ISODateTimeFormat.dateTime()
println fmt_out.print(fmt_in.parseDateTime(startTime))
sorry, newbie to groovy grails

After parsing for DateTime, you need to transform it to the desired type. For date and time without considering timezone I suggest you to use LocalDateTime and LocalTime.
def formatter = DateTimeFormat.forPattern("HH:mm:ss")
LocalTime time = formatter.parseLocalDateTime(params.startTime).toLocalTime()

Related

How to modify a date to meet correct groovy standard?

I am trying to parse the following date in Jenkins 2021-10-14T18:12:20.578+00:00 however, I am getting the error Unparseable date: "2020-01-01T10:10:20.578+00:00"
This is my code, not sure what I am doing wrong:
Date myDate= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse("2020-01-01T10:10:20.578+00:00");
EDIT:
Thanks to Kaus, I found that my date is not formatted properly and should be 2020-01-01T10:10:20.578GMT+00:00
I'm getting this date from some other files. I can replace + with GMT+ as follow:
def myDate = "2020-01-01T10:10:20.578+00:00"
myDate = myDate.replaceAll("\\+", "GMT\\+")
How can I do the same thing if my date is "2020-01-01T10:10:20.578-06:00"
The following is replacing every "-"
def myDate = "2020-01-01T10:10:20.578-06:00"
myDate = myDate.replaceAll("\\+", "GMT\\+").replaceAll("\\-", "GMT\\-")
Output: "2020GMT-01GMT-01T10:10:20.578GMT-06:00"
Use X for ISO8601 time zone, instead of Z for RFC 822 time zone.
(from https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html)
import java.text.SimpleDateFormat
Date myDate = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX")
.parse("2020-01-01T10:10:20.578+00:00")
Missing GMT there
Date myDate= new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").parse("2020-01-01T10:10:20.578GMT+00:00");

Getting datetime as a string in current timezone

In the MySQL DB: '2020-04-19 22:00:00'(UTC). That's also what my endpoint returns since I set the connection option dataStrings:true.
On the client, after I fetch date:
const timezone = moment.tz.guess();
const convertedDate = moment(date)
.tz(timezone)
.format();
convertedDate then equals to "2020-04-19T22:00:00+02:00" (I'm in the UTC+2 zone).
I would like to get it in the format "2020-04-20T00:00:00" instead. How can I do that?
It looks like moment(date) believes your incoming date value is in local time, not UTC. So, your timezone conversion to local time changes nothing. You can tell moment it's UTC, like this:
const timezone = moment.tz.guess();
const convertedDate = moment.utc(date)
.tz(timezone)
.format();
You do not need moment-timezone for this. With Moment by itself you can use the utc function when parsing, and the local function to convert to the user's local time zone before formatting.
moment.utc('2020-04-19 22:00:00').local().format()
//=> "2020-04-20T00:00:00+02:00"
Also, the Moment team recommends using Moment for existing projects only. For new development, we recommend using Luxon instead:
luxon.DateTime.fromSQL('2020-04-19 22:00:00', {zone: 'utc'}).toLocal().toISO()
//=> "2020-04-20T00:00:00.000+02:00"

Creating a timestamp in a Jenkinsfile

I'm struggling a little creating a timestamp in a format that I want using a scripted pipeline in Jenkins. Here's my code from the pipeline:
def cal = Calendar.instance
def dateFormat = 'YYYYMMDD-hhmmss'
def timeZone = TimeZone.getTimeZone('CST')
def timeStamp = cal.time​.format(dateFormat,timeZone)​
println "Timestamp is: ${timeStamp}"
env.BUILD_TIMESTAMP = timeStamp
When I run via Jenkins, I get the following:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field java.util.GregorianCalendar time​
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:387)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:371)
I've seen mention of similar issues with different fields online, but the workaround of adding it to scriptapproval.xml (and restarting Jenkins) doesn't seem to be working.
Anyone have a method of generating a timestamp in a format similar to what I'm trying to do?
I figured out a way around it. I was accessing the field time directly. If I change the call from cal.time to cal.getTime() Jenkins behaves a lot better. I consolidated it into a one-liner, but the functionality's the same:
def timeStamp = Calendar.getInstance().getTime().format('YYYYMMdd-hhmmss',TimeZone.getTimeZone('CST'))
Thanks to those that had a look.
Or use Date() formatted with SimpleDateFormat():
import java.text.SimpleDateFormat
def dateFormat = new SimpleDateFormat("yyyyMMddHHmmss")
def date = new Date()
def timestamp = dateFormat.format(date)

How to shift the timezone of an instance of the ruby Time object [duplicate]

I have a datestring in this format
yyyy-mm-ddThh:mm:ss[Z]
And i have a timezone string. for e.g "Asia/Kolkata"
Now i want to convert this date string into the timezone of the given timezone
for e.g. if the date is 2014-01-03T23:30:00Z , then in "Asia/Kolkata" timezone it will be 2014-01-04T05:00:00 .
I tried using Time library , but Time library does not seem to have any method which can convert to other timzone http://ruby-doc.org/core-1.8.6/Time.html#method-c-mktime .
You should use the TZInfo gem.
require 'tzinfo'
tz = TZInfo::Timezone.get('Asia/Kolkata')
utc = DateTime.iso8601('2014-01-03T23:30:00Z')
local = tz.utc_to_local(utc)
If it just a ruby project without rails, also you do not want to install third party gems.
Then you have to do it yourself, the following is what I did:
def convert_time_to_timezone(time, timezone)
timezone_in_hours = timezone.to_i
time_in_seconds = time.to_i
time_in_seconds_in_timezone = time_in_seconds + timezone_in_hours*3600
utc_time = Time.at(time_in_seconds_in_timezone).utc
Time.new(utc_time.year, utc_time.month, utc_time.day, utc_time.hour, utc_time.min, utc_time.sec, "#{timezone}:00")
end
Just provide time (e.g., Time.now) and timezone (e.g., "+11:00", or "-05:00")
it will return the time with the specified timezone.
example:
call convert_time_to_timezone(Time.now, "+11:00") it will return something like
2017-05-31 18:17:13 +1100
If it has rails installed, then you can directly call in_time_zone('"Central Time (US & Canada)"')

Saving and Querying a Date in GORM Grails

I have a database table TableA, which has a column 'theDate' for which the datatype in the database is DATE.
When I save a java.util.Date to 'theDate' through GORM it appears to save just the date value when I look at the data in the table by just executing select * from TableA.
However, when I run a query such as:
select * from TableA where theDate = :myDate
No results are found, but if I run something like;
select * from TableA where theDate <= :myDate
I do get results.
So it's like the Time is relevant.
My question is how do I save a Date and query for a Date ignoring the Time completely and just matching on an exact Date only?
Thanks.
note: I have also tried using sql.Date and util.Calendar but to no success.
clearTime()
You can use clearTime() before saving and before comparing to zero out the time fields:
// zero the time when saving
new MyDomain(theDate: new Date().clearTime()).save()
// zero the target time before comparing
def now = new Date().clearTime()
MyDomain.findAll('SELECT * FROM MyDomain WHERE theDate = :myDate', [myDate: now])
joda-time plugin
An alternative would be to install the joda-time plugin and use the LocalDate type (which only holds date information, no times) instead of Date. For what it's worth, I don't think I've worked on a project with dates without using the Joda plugin. It's completely worth it.
If you have date saved without clearing you could retrieve it using range, as Jordan H. wrote but in more simple way.
def getResults(Date date) {
def from = date.clearTime()
def to = from + 1
def results = MyDomain.findAll("from MyDomain where dateCreated between :start and :stop" ,[start:from,stop:to])
}
Your question may be a duplicate. See Convert datetime in to date. But if anyone has more recent information, that would be great.
If that doesn't help, you can hack it the way I might, with a BETWEEN restriction, e.g.
def today = new Date()
def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
def dateYmd = ymdFmt.format(today)
def dateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
def startDate = dateTimeFormat.parse("${dateYmd} 00:00:00");
def endDate = dateTimeFormat.parse("${dateYmd} 23:59:59");
MyDomain.findAll("from MyDomain where dateCreated between ? and ?", [startDate, endDate])
It's definitely not pretty, but it may get you where you're going.
I figured it out.
I used DateGroovyMethods.clearTime to clear the time value before saving.
You can use the DB type date not datetime , in the filed type

Resources