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.
Related
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.
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.
I tried to program date and time so that it corresponds to the current date but could not find a solution in the console, only the date of the last run is displayed. Here is my code:
public class DateDemo {
public static void main(String args[]) {
Date dNow = new Date();
SimpleDateFormat ft = new SimpleDateFormat("E dd.MM.yyyy 'um' HH:mm:ss ");
System.out.println("Datum: " + ft.format(dNow));
}
}
Consoles behave differently, so I’m afraid that there isn’t any universal solution.
I tried this:
DateTimeFormatter formatter
= DateTimeFormatter.ofLocalizedDateTime(FormatStyle.LONG)
.withLocale(Locale.GERMAN);
ZoneId timeZoneId = ZoneId.of("Europe/Zurich");
int totalIterations = Math.toIntExact(TimeUnit.HOURS.toSeconds(2));
for (int sec = 0; sec < totalIterations; sec++) {
System.out.print(ZonedDateTime.now(timeZoneId).format(formatter) + '\r');
TimeUnit.SECONDS.sleep(1);
}
When I run it inside Eclipse, it prints the lines under each other in the Eclipse console like this:
16. November 2019 07:37:32 MEZ
16. November 2019 07:37:33 MEZ
16. November 2019 07:37:34 MEZ
16. November 2019 07:37:35 MEZ
But when I run it from the Terminal window on my Mac, it stays on the same line and just keeps overwriting it:
The \rcharacter is a carriage return. In theory it should go back to the beginning of the same line. Maybe the reason why it doesn’t in Eclipse is they thought I wanted to use the console window for debugging and therefore would be better served if I could see all output, so they didn’t want to overwrite any. Just guessing.
There are more elegant and more accurate ways to make something happen every second. Look into ScheduledExecutorService.scheduleAtFixedRate.
PS The format differs a bit in the two screen shots, in the Terminal window um (“at”) is included between the date and the time. The difference comes from different Java versions. In Eclipse I used Java 8, in the Terminal window Java 11. The story is in this question: JDK dateformatter parsing DayOfWeek in German locale, java8 vs java9.
My system time zone is (UTC+02:00) Istanbul. When I run a simple java program to display time zone, it displays "America/Rio_Branco" (which is incorrect). But when I set to any other time zones it works correctly. Also I updated my jre using tzupdater.jar (I set my path to ..\jre\lib). What could be the reason?
My code is :
import java.util.*;
import java.text.*;
public class Time
{
public static void main(String[] args){
TimeZone timeZone = TimeZone.getDefault();
System.out.println("timeZone : "+timeZone);
}
}
I replaced tzmappings file with the one from jre8 and it solved my problem.
If you read the JavaDoc you'll see this:
Gets the default TimeZone for this host. The source of the default TimeZone may vary with implementation.
Thus reason you're getting "America/Rio_Branco" is because the JDK implementation for your host (operating system) thinks you are in Rio Branco's timezone. In the comments you mention you're running Windows 7, so it might be the case that Windows incorrectly has a timezone set somewhere. I think Java on Windows checks in the registry here:
HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Control/TimeZoneInformation
Maybe you can check that value?
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)