How to form java.util.Date calls in Clojure [duplicate] - java

This question already has answers here:
How to Convert A Clojure/Java Date to Simpler Form
(2 answers)
Closed 8 years ago.
I have been successfully using java.util.Date, and I would prefer to keep using it. Basically, I am having trouble forming the method calls to a class.
I basically want to feed a date like 2014-08-06 into my Clojure program which will override using today as the date. This is so I can form a SQL query. I'm just not sure how to use the Java calls in Clojure.
(def x1 (SimpleDateFormat. "yyyy-MM-dd"))
I just don't know how to form the parse.
Here's my core.clj
(ns util.core
^{:author "Charles M. Norton",
:doc "util is a Clojure utilities directory containing things
most Clojure programs need, like cli routines.
Created on April 4, 2012"}
(:require [clojure.string :as cstr]
[clojure.data.csv :as csv]
[clojure.java.io :as io])
(:import java.util.Date)
(:import java.text.SimpleDateFormat)
(:import java.text.ParseException)
(:import java.io.File)
(:use clojure-csv.core))
Here is the Java code
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
public class MainClass {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
GregorianCalendar gc = new GregorianCalendar();
java.util.Date d = sdf.parse("12/12/2003");

Here is parse call in lein repl
user=> (def x1 (SimpleDateFormat. "yyyy-MM-dd"))
#'user/x1
user=> (.parse x1 "2014-08-06")
#inst "2014-08-05T21:00:00.000-00:00"
user=> (type (.parse x1 "2014-08-06"))
java.util.Date
read http://clojure.org/java_interop to know how to translate java code.

Related

Java JodaTime: java.lang.NoClassDefFoundError: org/joda/time/Chronology

I am writing a basic Java program using JodaTime to convert a date from the Gregorian Calendar to the Islamic Hijri Calendar. However, when I run my code, I get the following error:
Error: Unable to initialize main class MainActivity Caused by:
java.lang.NoClassDefFoundError: org/joda/time/Chronology
Below is my code:
import org.joda.time.Chronology;
import org.joda.time.LocalDate;
import org.joda.time.chrono.IslamicChronology;
import org.joda.time.chrono.ISOChronology;
public class MainActivity {
public static void main(String[] args) {
Chronology iso = ISOChronology.getInstanceUTC();
Chronology hijri = IslamicChronology.getInstanceUTC();
LocalDate todayIso = new LocalDate(2021, 8, 17, iso);
LocalDate todayHijri = new LocalDate(todayIso.toDateTimeAtStartOfDay(),
hijri);
System.out.println(todayHijri);
}
}
This seems strange, considering that I have downloaded the latest joda time jar file from the official Joda Time release history on GitHub: https://github.com/JodaOrg/joda-time/releases (joda-time-2.10.10.jar), added it to the lib folder in my project, and added the jar file to my build path, as you can see in the file hierarchy below:
As #Abra stated, making sure the JAR file was on my run configuration in my classpath worked :D.

How to check the displayed date in Selenium with Java

I am trying to get the displayed date in the exact format to validate if it is in MM/dd/yyyy HH:mm. I tried :
element.getAttribute("value")
but that returns "yyyy-MM-ddTHH:mm" which actually is different than what is in UI.
Also when I use:
LocalDateTime currentDateTime = LocalDateTime.now();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("ddMMyyyy");
String date = dtf.format(currentDateTime);
works fine: screenshot
The data from the UI may have been converted into ISO-8601 format by the bootstrap library. Therefore, if you need to get the value in the MM/dd/yyyy HH:mm format, you can do so using a DateTimeFormatter.
Demo:
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
String input = "2021-06-01T04:05";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/uuuu HH:mm", Locale.ENGLISH);
String formatted = LocalDateTime.parse(input).format(formatter);
System.out.println(formatted);
}
}
Output:
06/01/2021 04:05
ONLINE DEMO
Learn more about the modern Date-Time API* from Trail: Date Time.
* For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7. If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.

How to Format English Date in Japanese with ERA

I want the new Japanese ERA Date as "R010501", whereas I am getting "R151".
I am using the com.ibm.icu.text.DateFormat package to get the date format
Date dtEngDate = new SimpleDateFormat("yyyy-MM-dd").parse("2019-05-01");
com.ibm.icu.util.Calendar japaneseCalendar = new com.ibm.icu.util.JapaneseCalendar();
com.ibm.icu.text.DateFormat japaneseDateFormat = japaneseCalendar.getDateTimeFormat(
com.ibm.icu.text.DateFormat.SHORT, -1, Locale.JAPAN);
String today = japaneseDateFormat.format(dtEngDate);
System.out.println("today is:" +today.replaceAll("/", ""));
Output: today is --> R151.
Expected Output: today is --> R010501
I don't know what exactly you did other than me but I just downloaded the com.ibm.icu library from http://www.java2s.com/Code/Jar/c/Downloadcomibmicu442jar.htm and basically copied your code.
import com.ibm.icu.text.DateFormat;
import com.ibm.icu.util.Calendar;
import com.ibm.icu.util.JapaneseCalendar;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class Main {
public static void main(String[] args) throws ParseException {
Date dtEngDate = new SimpleDateFormat("yyyy-MM-dd").parse("2019-05-01");
Calendar japaneseCalendar = new JapaneseCalendar();
DateFormat japaneseDateFormat = japaneseCalendar.getDateTimeFormat(DateFormat.SHORT, -1, Locale.JAPAN);
String today = japaneseDateFormat.format(dtEngDate);
System.out.println("today is: " + today.replaceAll("/", ""));
}
}
I'm getting today is: 平成310501 as console output and I guess this is what you are looking for. So I guess there is something wrong with your com.ibm.icu-4.4.2.jar.
Maybe consider retrying to download the latest version from the link I used and adding it to the modules/projects dependencies.
java.time.chrono.JapaneseDate
You don’t need an external dependency for the Japanese calendar. It’s built-in, in the JapaneseDate class.
Beware: Only the most recent versions of Java know about the new Reiwa era.
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("GGGGGyyMMdd", Locale.JAPANESE);
LocalDate isoDate = LocalDate.parse("2019-05-01");
JapaneseDate japaneseDate = JapaneseDate.from(isoDate);
System.out.println(japaneseDate.format(dateFormatter));
Output from this snippet on Java 11.0.3 is:
R010501
Five pattern letters G gives the narrow form of the era, just one letter (here R for Reiwa).
On Java 9.0.4 I got H310501. So it seems that it will work correctly if you are able to upgrade your Java. Meno Hochschild reports in a comment that he got the correct result on Java 8u212, so you may not need to upgrade to a new major version if only you’ve got the newest minor upgrade within your major version. I don’t know if there’s a way to upgrade only the calendar data in an older Java version, it might be another thing to investigate.
BTW don’t use SimpleDateFormat and Date. Those classes are poorly designed (the former in particular notoriously troublesome) and long outdated. Use java.time, the modern Java date and time API. It’s so much nicer to work with.
Link: Oracle Tutorial: Date Time explaining the use if java.time.

Why am I getting a ParseException when using SimpleDateFormat to format a date and then parse it?

I have been debugging some existing code for which unit tests are failing on my system, but not on colleagues' systems. The root cause is that SimpleDateFormat is throwing ParseExceptions when parsing dates that should be parseable. I created a unit test that demonstrates the code that is failing on my system:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
import junit.framework.TestCase;
public class FormatsTest extends TestCase {
public void testParse() throws ParseException {
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS Z");
formatter.setTimeZone(TimeZone.getDefault());
formatter.setLenient(false);
formatter.parse(formatter.format(new Date()));
}
}
This test throws a ParseException on my system, but runs successfully on other systems.
java.text.ParseException: Unparseable date: "20100603100243.118 -0600"
at java.text.DateFormat.parse(DateFormat.java:352)
at FormatsTest.testParse(FormatsTest.java:16)
I have found that I can setLenient(true) and the test will succeed. The setLenient(false) is what is used in the production code that this test mimics, so I don't want to change it.
--- Edited after response indicating that the developer is using IBM's J9 1.5.0 Java Virtual Machine ---
IBM's J9 JVM seems to have a few bugs and incompatibilities in the parse routine of DateFormat, which SimpleDateFormat likely inherits because it is a subclass of DateFormat. Some evidence to support that IBM's J9 isn't functioning quite the way you might expect other JVMs (like Sun's HotSpot JVM) can be seen here.
Note that these bugs and incompatibilites are not even consistent within the J9 JVM, in other words, the IBM J9 formatting logic might actually generate formatted times that are not compatible with the IBM J9 parsing logic.
It seems that people who are tied to IBM's J9 JVM tend to work around the bug in the JVM by not using DateFormat.parse(...) (or SimpleDateFormat.parse(...)). Instead they tend to use java.util.regex.Matcher to parse the fields out manually.
Perhaps a later release of the J9 JVM fixes the issue, perhaps not.
--- Original post follows ---
Funny, the same code modified to:
import java.util.Date;
import java.util.TimeZone;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
import java.text.ParseException;
public class FormatsTest {
public void testParse() throws ParseException {
DateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss.SSS Z");
formatter.setTimeZone(TimeZone.getDefault());
formatter.setLenient(false);
System.out.println(formatter.format(new Date()));
formatter.parse(formatter.format(new Date()));
}
public static void main(String[] args) throws Exception {
FormatsTest test = new FormatsTest();
test.testParse();
}
}
runs fine on my system. I would wager that it is something in your environment. Either you are compiling the code on one JVM major release and running it on another (which can cause some issues as the libraries could be out of date) or the system you are running it on might be reporting the time zone information oddly.
Finally, you might want to consider if you are using a very early point release of the JVM. Sometimes bugs do creep into the various versions, and they are fixed in later point releases. Could you please modify your question to include the "java -version" information for you system?
Either way, both of these are just educated guesses. The code should work as written.
That should probably be a bug in IBM's J9 VM about the SimpleDateFormat class.
This post show a similar problem, and says it should be fixed on v6.
You may find the list of changes for several releases here.
I see there's a number related to DateFormat. So, you should probably raise a bug report or something with IBM for them to give you a patch.
Check the LANG environment variable of your computer and of the remote computer.
The date is parsed according to the locale, so 'Jul' works as July only if your LANG is set to english, otherwise a ParseException is raised.
You can make a quick test by running export LANG="en_US.UTF-8" and then running your program.
You can also set the locale programmatically, by using the following method:
DateFormat.getDateInstance(int, java.util.Locale)

Embedding swank-clojure in java program

Based on the Embedding section of http://github.com/technomancy/swank-clojure,
I'm using the following to test it out. Is there a better way to do
this that doesn't use Compiler? Is there a way to programmatically
stop swank? It seems start-repl takes control of the thread. What
would be a good way to spawn off another thread for it and be able to
kill that thread programatically.
import clojure.lang.Compiler;
import java.io.StringReader;
public class Embed {
public static void main(String[] args) throws Exception {
final String startSwankScript =
"(ns my-app\n" +
" (:use [swank.swank :as swank]))\n" +
"(swank/start-repl) ";
Compiler.load(new StringReader(startSwankScript));
}
}
Any help much appreciated,
hhh
Would it be acceptable to you to implement the Embed class in Clojure? You could do that with gen-class (see Meikel Brandmeyer's tutorial for details) and AOT compilation.
The code could go something like
(ns your-app.Embed
(:require [swank.swank :as swank])
(:gen-class
:methods [[startSwank [] void]]))
(defn -startSwank []
(swank/start-repl))
(add anything else you require); then in the Java part of your application, you could import your Clojure-prepared class, instantiate it and call .startSwank() on the instance.
Not sure about programmatically stopping Swank... I'd be curious to know of a good way to do that myself. (And I'll be back with an update if I figure it out; otherwise, I'd love to read somebody else's answer detailing how to go about that.)

Categories

Resources