All day event icalendar gem - ruby-on-rails

I am using the below to setup an event to export to ical with the icalendar gem.
#calendar = Icalendar::Calendar.new
event = Icalendar::Event.new
event.dtstart = ev.start_at.strftime("%Y%m%d")
event.dtend = ev.end_at.strftime("%Y%m%d")
event.summary = ev.summary
#calendar.add
In order to make an event all day it needs to look like this:
DTSTART;VALUE=DATE:20101117
DTEND;VALUE=DATE:20101119
Right now I am using
event.dtstart = "$VALUE=DATE:"+ev.start_at.strftime("%Y%m%d")"
This will output
DTSTART:$VALUE=DATE:20101117
and then I replace all ":$" with ";" with
#allday = #calendar.to_ical.gsub(":$", ";")
Is there a more direct way to save dates as all day?

I played around with this and figured out one way. You can assign properties to the event dates, in the form of key-value pairs. so you could assign the VALUE property like so:
event = Icalendar::Event.new
event.dtstart = Date.new(2010,12,1)
event.dtstart.ical_params = { "VALUE" => "DATE" }
puts event.to_ical
# output
BEGIN:VEVENT
DTSTAMP:20101201T230134
DTSTART;VALUE=DATE:20101201
SEQUENCE:0
UID:2010-12-01T23:01:34-08:00_923426206#ubuntu
END:VEVENT
Now the fun part. Given a calendar you can create an event and pass in a block which initializes the date with its properties:
calendar.event do
dtstart Date.new(2010,11,17), ical_params = {"VALUE"=>"DATE"}
dtend Date.new(2010,11,19), ical_params = {"VALUE"=>"DATE"}
end

So this thread seems quite old (and did not solve the problem with the most recent version of the icalendar gem - 2.3.0). I've recently had to create "all day" calendar events in ics format. I've found this to be a much better solution (and seems to work the way you'd expect calendars to handle it) - see the snippet below
date = Date.new(2010,11,17)
event = Icalendar::Event.new
event.dtstart = Icalendar::Values::Date.new date
event.dtstart.ical_param "VALUE", "DATE"
event.dtend = Icalendar::Values::Date.new (date + 1.day)
event.dtend.ical_param "VALUE", "DATE"
puts event.to_ical
The above code produces the following output:
BEGIN:VEVENT
DTSTAMP:20150521T162712Z
UID:4c239930-15ba-44b4-a045-c6fae3d858d2
DTSTART;VALUE=DATE:20101117
DTEND;VALUE=DATE:20101118
END:VEVENT
Note that the Date does not have a time associated with it. The code in the prior reply currently produces the time. I had to dig into the source code for icalendar to figure out this solution.
I hope this helps someone else.
Cheers!

Related

Nokogiri parsing a datetime

I am doing a scraping in a website and get stucked on this:
inside_doc.css('.listing-header-container').at_css("h3 time").to_s
=> "<time datetime=\"2018-08-10T16:49:03Z\" data-local=\"time\" data-format=\"%b %e\">Aug 10</time>"
Im trying to get this 'datetime'element to add to my model. In this case I want to get this value:
2018-08-10T16:49:03Z\
In my model I have a attribute called:
#my_model.date_of_publication = 2018-08-10T16:49:03Z\
How can I do this in Nokogiri?
I just found. Just add a #datetime to the parsing
inside_doc.css('.listing-header-container').at_css("h3 time #datetime").to_s
It should look like this:
dt = page.at('time[datetime]')['datetime']
and then you can parse that with Chronic:
time = Chronic.parse dt

How do I use Icalendar::HasComponents?

Regarding https://github.com/icalendar/icalendar/pull/132: Given that I have a
#cal = Icalendar::Calendar.new
How do I use Icalendar::HasComponents to add X-WR-CALNAME, X-PUBLISHED-TTL and X-WR-CALDESC properties to #cal?
I want to generate these extra properties in my .ics file so that I could add it to Google Calendar and Outlook and allow them to specify
X-WR-CALNAME - calendar name
X-PUBLISHED-TTL - refresh interval
X-WR-CALDESC - calendar description
It's simpler than I thought:
cal = Icalendar::Calendar.new
cal.append_custom_property("X-WR-CALNAME","My Calendar")
cal.append_custom_property("X-PUBLISHED-TTL","PT1H") # every hour
cal.append_custom_property("X-WR-CALDESC","My Desc")
Reference: https://github.com/icalendar/icalendar/blob/master/lib/icalendar/has_properties.rb

Grails - Convert String data to Date

Lets say, i have a "Book" class with field "availableOn"(as shown below).
class Book {
String availableOn;
}
The fields holds values
"All days" or
String representation of a date. For example "13/06/2012"
How can i get all Books that are available within next two days? The below code would throw an exception ("java.util.Date cannot be cast to java.lang.String")
def books = c.list(){
between('availableOn', new Date(), new Date() + 2)
}
PS : Am working on a legacy DB, and so am not suppose to change the schema :(
I think there are 2 problems which the between statement will have:
availableOn cannot be converted to a Date for comparison when its value is All days
Even when availableOn has a date value in it, it is not converted to a Date for the comparison
I'd try something along the lines of this:
def now = new Date()
def books = Book.findAllByAvailableNotEqual("All days").findAll { book ->
Date.parse('dd/MM/yyyy', book.availableOn) > now && Date.parse('dd/MM/yyyy', book.availableOn) < now+2
}
Clearly, this can be done in a nicer way (adding some methods to the domain class for example), but this should illustrate my idea...
I don't have a criteria based solution, but you can try something like this:
Book.executeQuery(
"select book from Book book where book.availableOn = :availableOn or to_date(book.availableOn, :format) between (:startDate, :endDate) ",
[availableOn:"All days", format: "dd/MM/yyyy", startDate: startDate, endDate:endDate])
The problem with my solution is that this query becomes DB dependent. to_date is an Oracle function. You may want to alter this to fit your database
You can use format on a date to get desired string format of it.
new Date().format('dd/MM/yyyy')
And your criteria would get modified to
def books = c.list(){
def todayDateStr = new Date().format('dd/MM/yyyy')
def twoDaysAfterTodayDateStr = (new Date()+2).format('dd/MM/yyyy')
or{
between('availableOn', todayDateStr, twoDaysAfterTodayDateStr)
eq 'availableOn', 'All Days'
}
}
Test if the str comparison works, otherwise other ways has to be used. Sending from phone, excuse my typos.
UPDATE
The above would fail in peculiar cases when dates are like "01/01/2013" and "07/11/2011".
Alternatively, you can use sqlRestriction but in that case it gets tightly coupled with the underlying database. Something like this can be done if Oracle db is used:
def books = c.list(){
def todayDateStr = new Date().format('dd/MM/yyyy')
def twoDaysAfterTodayDateStr = (new Date()+2).format('dd/MM/yyyy')
or{
sqlRestriction "to_date(available_on, 'DD/MM/YYYY') between to_date(todayDateStr, 'DD/MM/YYYY') and to_date(twoDaysAfterTodayDateStr, 'DD/MM/YYYY')"
eq 'availableOn', 'All Days'
}
}

Merge Time into a DateTime to update Datetime

I need to update time info in a DateTime.
I get a string in the format "14" or "14:30" (for example), so I need to give it to Time parser to get the right hour. Then I need to update self.start_at which is a datetime which already has a time, but I need to update it.
self.start_at_hours = Time.parse(self.start_at_hours) # example 14:30:00
# NEED TO UPDATE self.start_at which is a datetime
I was using the change method on self.start_at but it only takes hour and minutes separated and I'm not sure what should I do.
Have you thought about doing somethings like this?
time_to_merge = Time.new
date_to_merge = Date.today
merged_datetime = DateTime.new(date_to_merge.year, date_to_merge.month,
date_to_merge.day, time_to_merge.hour,
time_to_merge.min, time_to_merge.sec)
For replacing time, the .change() method should work, like this:
my_datetime = my_datetime.change(hour: my_time.hour, min: my_time.min, sec: my_time.sec)
For adding time, try converting to seconds and then adding them:
my_datetime += my_time.seconds_since_midnight.seconds

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