Clojure - parse string to date - parsing

I'm trying to parse a unformatted string which contains a date (e.g. today = "08082013") to the format "08.08.2013".
This works:
(.parse (java.text.SimpleDateFormat. "ddMMyyyy") today) => <Date Sun Jan 01 00:00:00 CET 1950>
But when I do (.parse (java.text.SimpleDateFormat. "dd.MM.yyyy") today) I get the error "Unparseable date: "08082013"
Why? How can I get my desired date format?

To get from string to date, use parse.
To get from date to string, use format.
Both use a formatter to describe the transition.
=>(.format
(java.text.SimpleDateFormat. "dd.MM.yyyy")
(.parse
(java.text.SimpleDateFormat. "ddMMyyyy")
"08082013"))
"08.08.2013"

If you are playing around with date and time I recommend checking out this Clojure lib,
https://github.com/clj-time/clj-time
It is kind of the time lib most Clojure programmers use, and is based on the java lib joda time, that by many is agreed to be better than the Java build in one.

The .parse method of SimpleDateFormat will not generate a string, it will read a string and generate a java.util.Date object. If you want to generate a dotted string, you need SimpleDateFormat with the dots in place and call .format on it, given a java.util.Date.
See http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html or take a look at clj-time

Using clj-time, you can use this:
(defn format-date
[date-str]
(f/unparse (f/formatter "dd.MM.yyyy") (f/parse custom-formatter date-str)))
(format-date "08082013") ;=> "08.08.2013"

Clojure is based on Java, so many of your options will end up calling Java in the end. The way I understand it, Java has two time apis. The old one is at java.text.SimpleDateFormat and is not recommended anymore. The new one is under java.time and is "much better".
With that in mind, you have several options for date manipulation in Clojure:
You can call either the new or old Java functions directly. NeilsK's answer provides examples on how to do this with the old api. You should be able to adapt it fairly easily to the new java.time api with some help from the Clojure documentation on java interop.
Everyone is saying use clj-time but I would not recommend it as it's based on a Java library called JodaTime which was deprecated when Java's new time API came out.
I personally have had a lot of success with a library called clojure.java-time which is a simple Clojure wrapper for Java's new time api.
juxt/tick looks very promising as it seeks to provide that new api in a clojure-friendly format across not only java platforms, but also in the browser and on dotnet. It was in alpha at the time of this writing but I will be keeping an eye on it.

Related

Twilio fetch all call logs from last 5 days in ruby

I want to fetch the call logs for the last 5 days, I read on the documentation
You can also specify an inequality, such as EndTime<=YYYY-MM-DD, to read calls that ended on or before midnight of this date
I am trying the following with no luck
#client.calls.list(to: phone_number, end_time: ">=#{Time.now - 5.days}")
Twilio developer evangelist here.
There are several things here, and I need to apologise for at least one of them.
Firstly, the less than/greater than equal that the Twilio API implemented was actually a bit of a hack with the way the parameters are formatted. The parameter as the docs point out is EndTime<=YYYY-MM-DD but this is made of the parameter name EndTime< and the parameter value YYYY-MM-DD separated by =. I apologise that this seemed like a cool hack but actually made things harder.
The Ruby library actually tries to unpick this and make it more sensible again. You can use the parameter end_time_after instead of trying to form the correct end_time format.
Second, I ran the string you were using for the end_time and it produced this:
irb(main):001:0> ">=#{Time.now - 5.days}"
=> ">=2021-02-28 14:35:44 +1100"
So when a time is stringified in Ruby, it doesn't just show up in the YYYY-MM-DD format.
So, to fix your API call, should format the date to YYYY-MM-DD and use end_time_after. Note, since you're using ActiveSupport, you can also call on 5.days.ago instead of Time.now - 5.days.
This should work for you:
#client.calls.list(to: phone_number, end_time_after: "#{5.days.ago.strftime("%Y-%m-%d")}")
Let me know if this helps at all.

Grails Timepicker

I need to save Date Time in the (oracle) database in one column, which is sqlType of timestamp (looks like 01-JAN-14 12.00.00.000000 AM). While learning grails I've been using the Joda lib with it's "time picker".
The Joda timepicker has worked well, but now that I'm looking to go primetime I'm looking for something a little more user friendly. Frankly, text boxes might be more user friendly than the drops downs joda gives you.
Anyway, I'd like to remove joda and use something like this:
http://trentrichardson.com/examples/timepicker/
but I can't figure out how to implement it in grails. In my view, if I put:
<input type="text" name="endDate" id="endDate" value="${exampleInstance?.endDate}" />
in place of the g:datePicker, it works fine (the picker that is), except nothing gets saved to the database, and no errors are generated. I hit Save and the Show view comes up with an empty endDate field. Do I need more input tags?
Is there some easy way to implement a modern looking date+time picker that I've missed?
Furthermore, I see there is a plugin for this picker here
http://grails.org/plugin/jquery-ui-timepicker
But being that there isn't any documentation, I'm not sure how to use that either (?)
ANSWER
in controller save/update put something like:
def endDate = params.date('endDate', 'yy-MM-dd h:mm')
//println "Date from Picker was "+endDate
params.endDate = endDate
No further casting was necessary being that it ended up I could format the datepicker control to a very close format as what's in the database, but had I needed to cast from one odd format, or a string, to another, I toyed with this code, which is more psuedo than anything as I was thinking through the process (I'm sure there's a totally Groovy way to do this same thing):
SimpleDateFormat inputFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss.S");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy h.mm.ss.S a");
def v = params.endDate
Date date = inputFormat.parse(v);
String temp = sdf.format(date)
Date dateOut = sdf.parse(temp)
println dateOut
The datepicker, is your UI component therefore, you can have any library that you wish for UI and anything else for back-end. Mostly they are easy to implement, if they provide a little bit of documentation!!.
The timepicker for jQuery ui plugin, that you provided the link, is exposing a resource called jqueryUiTimePicker which depends on jQuery and jQuery-ui. So simply by including this resource into you resources configuration you should be able to utilize it. Its no different than defining your own resource and use it.
About saving issue that you have, on your save pass parameter failOnError:true so you can see the errors if any.
I have created a sample project that utilizes this plugin hope it helps
In your controller, you will need to parse the parameter value to a Date value. Something like,
def endDate = params.date('endDate', 'dd-MM-yyyy')
dd-MM-yyyy is whatever format the jquery plugin submits the date value. (println params for this or look up the plugin documentation)
If you want a date format binding to happen automatically, check the Date Formats For Data Binding in the doc http://grails.org/doc/latest/guide/single.html#dataBinding for a way to globally specify the format

Generate RFC-2445 VTIMEZONE component for iCalendar

I'm currently attempting to understand without much success the implementation of VTIMEZONE component using the iCalendar gem.
I'm generating an ics formatted event calendar, unfortunately when importing event in Google Calendar (as an example), I'm getting wrong date and time due to the missing VTIMEZONE component in the generated calendar.
Writing down the VTIMEZONE component plain text is not really difficult, but I would like to be generated dynamically depending on a ActiveSupport::TimeZone I set in the application.
I explored several leads without success. The closer I came was to get the TZInfo object using ActiveSupport::TimeZone.find_tzinfo() method. But then how can I get the various component items needed to declare both Daylight and Standard VTIMEZONE component?
Is there any gem existing or can I do it natively using TZInfo. Going through all ruby docs I could find didn't help much. Any advice, leads are welcome.
Never mind, there is something existing in icalendar that does that.
https://github.com/icalendar/icalendar/blob/master/lib/icalendar/tzinfo.rb
Did not dig deep enough the first time.
require 'icalendar/tzinfo'
estart = DateTime.new(2008, 12, 29, 8, 0, 0)
tstring = "America/Chicago"
cal = Calendar.new
tz = TZInfo::Timezone.get(tstring)
timezone = tz.ical_timezone(estart)
cal.add(timezone)
cal.event do
...
end
cal.to_ical

JavaMail: how to get new messages comparing with time-stamps

I'm trying to get messages after a certain time-stamp, the way I've coded it was suggested by another programmer in this site:
GregorianCalendar date = new GregorianCalendar();
SearchTerm newer = new ReceivedDateTerm(ComparisonTerm.GT,date.getTime());
Message msgs[] = folder.search(newerThen);
The issue is that I get all the messages since the date, not the specific time. I was wondering if there is some work-around to emulate this. I mean, for an instance, if I want to get all the messages since today in the midday I would get those messages spicifically and not those ones received in today's morning.
Thanks in advance,
EDIT:
A new thought concerning to this: perhaps some date manipulation could do the job. I mean, comparing the minutes in the timestamp and filter programmatically those messages that don't fit the criteria. I know it's not the best way, but it could work.
PS: I'm using IMAP and trying to get mails from gmail, but I guess it should work no matter what the mail-server is.
Unfortunately, no. In this case, the IMAP protocol is being used by the JavaMail classes, and IMAP's SEARCH command takes only dates, not times (see the SINCE and SENTSINCE criteria).
You could use the setTime() method to query for some specific time.
Example:
setTime(timeInMilliseconds)

Parse a pdf file

I got a pdf like this one :
81 11005589 THING MAXIME 4 PC2I TR1 - MERCREDI DE 07H45 A 09H45 4A7
71 11007079 STUFF QUENTIN 1 PC2I TR1 - LUNDI DE 10H00 A 12H00 1B4
74 10506940 HAHA YEZHOU 2 PC2I TR1 - LUNDI DE 13H30 A 15H30 2D5
http://i.stack.imgur.com/hbXg2.png
And I need to parse it. What I mean by that is take the 4th column, add the 3rd column and make an email adress out of it. For example with the first line : maxime.thing#something.com
I tried to c/p it to Google docs but it just c/p it in one cell instead of multiple cells.
I really don't know what to do here. I guess regex would help me but with what ?
If it is Java iText, if it is C# iTextSharp, both are free for non commercial use.
I've used Aspose before for parsing PDFs/Word docs/Excel docs/and some other docs before. I'm not sure what their capabilities are when it comes to parsing tables in a PDF but it wouldn't surprise me if they had something.
I'd start by looking at them but be warned: they have an unapologetically piss poor method for updating their libraries. I have had to rewrite code because they flat out DROP functionality when they release new versions. Not deprecated, just GONE. That said their support is alright and the tool-set is quite powerful.
I know they have libraries for .NET and Java. Beyond that I can't say.
If in PHP, you can use
exec('pdftotext '.$filepath, $outputAsArray); //execute the command pdftotext. Proabably installed if you're on linux, if not you can install it /// to transform the pdf to text,
then
$text = implode($outputAsArray,"\n"); //to have the output as text
then preg_replace is your friend.
You can't just use a regular expression to parse PDF. You need to extract the text. There are many libraries that can do this for different languages.
My company, Atalasoft, has a text extraction add-on for .NET -- http://www.atalasoft.com/products/dotimage/pdf-reader
For Java, take a look at PDFTextStream from Snowtide. http://www.snowtide.com.
You cannot be sure there is any structure in the PDF of that the text is visible. You really need to use an extraction tool. I wrote an article explaining what formatting is actually in a PDF file at http://www.jpedal.org/PDFblog/?p=228

Resources