How to convert Japanese date into English date format? - java

I set Japanese date using Locale (e.g. 21 11月 2016) in my android app. But, I want to send that date into "dd-MM-yyyy" (e.g. 21-11-2016) format to my APIs.
When I try to do this I get below exception :
java.lang.IllegalArgumentException: Bad class: class java.lang.String
Below is my code :
public String convertDate(String date) {
System.out.println("......ORIGINAL DATE....... " + date); // ......ORIGINAL DATE....... 21 11月 2016
String myFormat = "dd-MM-yyyy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, new Locale(getMyLocale())); //Japanese locale is set but tried english too
System.out.println("......CONVERTED DATE....... " + sdf.format(date)); //should be 21-11-2016 but getting above error
return sdf.format(new Date(date));
}
Moreover, for US/English Locale it works fine but for Japanese I am getting this error.

You need two formatters as below
String in = "2016年11月 21日"; // really a space here?
SimpleDateFormat sdf1 = new SimpleDateFormat ("yyyy年MM月 dd日");
Date d1 = sdf1.parse(in);
SimpleDateFormat sdf2 = new SimpleDateFormat ("dd-MM-yyyy");
System.out.println(sdf2.format(d1));

java.time
You are using the troublesome old legacy date-time classes supplanted by java.time classes.
Define a DateTimeFormatter object to match the pattern of your input strings and specify a Locale for Japan. Parse input string into a LocalDate object. Call LocalDate.parse.
Define a DateTimeFormatter object to match your desired output. Call LocalDate::format to generate a string you desire.
This has been documented many times already in StackOverflow. Please search to find example code and further discussion.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Related

gregorian calendar java error

I can't print GregorianCalendar
package Tests;
import java.util.Date;
import java.util.GregorianCalendar;
public class Data
{
public static void main(String[] args)
{
GregorianCalendar time = new GregorianCalendar(1999, 2, 2);
System.out.println(time);
}
}
I receive this
java.util.GregorianCalendar[time=?,areFieldsSet=false,areAllFieldsSet=false,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Europe/Belgrade",offset=3600000,dstSavings=3600000,useDaylight=true,transitions=119,lastRule=java.util.SimpleTimeZone[id=Europe/Belgrade,offset=3600000,dstSavings=3600000,useDaylight=true,startYear=0,startMode=2,startMonth=2,startDay=-1,startDayOfWeek=1,startTime=3600000,startTimeMode=2,endMode=2,endMonth=9,endDay=-1,endDayOfWeek=1,endTime=3600000,endTimeMode=2]],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=?,YEAR=1999,MONTH=2,WEEK_OF_YEAR=?,WEEK_OF_MONTH=?,DAY_OF_MONTH=2,DAY_OF_YEAR=?,DAY_OF_WEEK=?,DAY_OF_WEEK_IN_MONTH=?,AM_PM=0,HOUR=0,HOUR_OF_DAY=0,MINUTE=0,SECOND=0,MILLISECOND=?,ZONE_OFFSET=?,DST_OFFSET=?]
How I can print it?
you can use this like :-
GregorianCalendar calendar = new GregorianCalendar();
Date now = calendar.getTime();
System.out.println(now);
or
Calendar cal2 = new GregorianCalendar(2010, 9, 26); // allocate with the specified date
cal2.get(Calendar.DAY_OF_WEEK); // 1 (Sunday) to 7 (Saturday)
when you call
System.out.println(time)
you've actually calling the toString() method of the Calendar instance (in this case, a GregorianCalendar one)
In order to have a properly formatted date, use SimpleDateFormat as stated in the Javadoc
https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html
java.time
The modern solution uses the LocalDate class instead. Avoid GregorianCalendar as it is now obsolete.
LocalDate ld = LocalDate.of( 1999 , Month.FEBRUARY , 2 ) ;
ld.toString(): 1999-02-02
The toString method uses the standard ISO 8601 formats. For other formats, use the DateTimeFormatter class. Search Stack Overflow for more examples and discussion, as that has beeen covered many many times.
Generally best to let DateTimeFormatter automatically localize for you.
Locale locale = Locale.CANADA_FRENCH ;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDate( FormatStyle.FULL ).withLocale( locale ) ;
String output = ld.format( f ) ;
mardi 2 février 1999
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Unexpected exception while parsing date

I am trying to parse the date according to the following code but getting exception. Below is the code -
public class DateTest {
public static void main(String args []) {
String start = "23-Jan-2017";
DateFormat dateFormatTripStartDate = new SimpleDateFormat("dd-MMM-yyyy hh:mm a");
try {
Date parsedDate = dateFormatTripStartDate.parse(start);
System.out.println(parsedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Exception :
java.text.ParseException: Unparseable date: "23-Jan-2017"
at java.text.DateFormat.parse(DateFormat.java:357)
at DateTest.main(DateTest.java:18)
Kindly help me identify the problem. Thanks.
Remove the time part in your pattern:
DateFormat dateFormatTripStartDate = new SimpleDateFormat("dd-MMM-yyyy");
tl;dr
LocalDate.parse(
"23-Jan-2017" ,
DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US )
)
Using java.time
Other Answers are correct about formatting pattern mismatching input data. But both the Question and other Answers are outdated.
The modern way is with java.time classes that supplant the troublesome old date-time classes.
The LocalDate class represents a date-only value without time-of-day and without time zone.
DateTimeFormatter f = DateTimeFormatter.ofPattern( "dd-MMM-uuuu" , Locale.US );
LocalDate ld = LocalDate.parse( "23-Jan-2017" , f );
ld.toString(): 2017-01-23
Specify the Locale as that determines the human language used to translate the name of the month. If omitted the JVM’s current default Locale is used implicitly. That default can be changed at any moment by any code in any thread of any app within the JVM, so do not rely upon it.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, andfz more.
First of all, the answer from kamehl23 is correct. Your parsed string may not be missing any parst that are specified in format and thus you will need to modify your format to DateFormat dateFormatTripStartDate = new SimpleDateFormat("dd-MMM-yyyy"); However just to add few more interesting options: Remember that SimpleDateFormat is not thread safe and in general not recommended. Sensible pre Java 8 options are Apache FastDateFormat and joda-time package. Both have some problems but certainly by far better then SimpleDateFormat (Joda-time package is very popular). In Java 8 a new date and time hanling was introduced with package java.time.format It takes time to adjust to it but it works wonderful and resolves many problems that existed in that area. See class DateTimeFormatter.And finally, I once had to write a utility that can take a String in any format and attempt to parse it to Date if possible. I wrote an article that describes how I implemented that Utility. I wrote it in Java 8, but the idea could be implemented in any version. See Java 8 java.time package: parsing any string to date
You are using pattern "dd-MMM-yyyy hh:mm a". But in actual "hh:mm a" part is not present in the "23-Jan-2017" value. Because of this parse function is not able to parse the String date.
So change your pattern to "dd-MMM-yyyy" which matches your date string. This will remove the exception you are getting.

How do I print a millisecond count from epoch as a date-time in UTC using Java?

I am trying to use Java to format a time in milliseconds into a date in UTC. I have the following code:
long ms = 1427590800000;
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"), Locale.ROOT);
cal.setTimeInMillis(ms);
Date date = cal.getTime();
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd hh:mm:ss");
System.out.println(dateFormat.format(date)); // 2015-03-29 02:00:00
This is printing a time in BST (i.e. using the default time-zone) rather than UTC. It seems like the time-zone being set on the calendar has no bearing on the date being printed.
The actual time in UTC is shown by the following python snippet:
import datetime
ms = 1427590800000
print datetime.datetime.utcfromtimestamp(ms/1000.0) # 2015-03-29 01:00:00
Setting the default JVM time-zone to "UTC" results in the correct date being printed, but this doesn't seem like a safe solution.
java.time
The modern approach uses the industry-leading java.time classes.
Parse as an Instant, a moment in UTC with a resolution of nanoseconds.
long input = 1_427_590_800_000L ;
Instant instant = Instant.ofEpochMilli( input ) ;
ISO 8601
Generate a string in standard ISO 8601 format.
String output = instant.toString() ;
2015-03-29T01:00:00Z
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
You need to set the timezone to the formatter before formatting if you want a desired timezone.
Use dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); and then call dateFormat.format(date)

Formatting Date in Thread safe Manner throws java.text.ParseException:

I am trying to convert the date from one format to Another
Input String - 2012-11-07-121603 (yyyy-MM-dd-HH-mm-ss)
Output String - 2012-11-07-12:16:03:000 (yyyy-MM-dd-HH:mm:ss:SSS)
ThreadSafeSimpleDateFormatUtil simpleDateFormat = new ThreadSafeSimpleDateFormatUtil(GenericConstants.DATE_FORMAT.YYYY_MM_DD_HH_MM_SS.toString());
final Date parsedDate = simpleDateFormat.parse(bulkCollectionTime);
simpleDateFormat = new ThreadSafeSimpleDateFormatUtil(GenericConstants.DATE_FORMAT.YYYY_MM_DD_HH_MM_SS_SSS.toString());
writeBean.setTimestamp(simpleDateFormat.format(parsedDate));
But it's throwing below error:
java.text.ParseException: Unparseable date: "2012-11-07-121603"
at java.text.DateFormat.parse(DateFormat.java:337)
at com.belgacom.rosy.rebecca.utils.ThreadSafeSimpleDateFormatUtil.parse(ThreadSafeSimpleDateFormatUtil.java:39)
Looks like the input format should be without the "-" between hours, minutes and seconds:
2012-11-07-121603 (yyyy-MM-dd-HHmmss)
Input String - 2012-11-07-121603 (yyyy-MM-dd-HH-mm-ss)
wrong pattern it would match with yyyy-MM-dd-HHmmss.
tl;dr
LocalDateTime.parse(
"2012-11-07-121603" ,
DateTimeFormatter.ofPattern( "uuu-MM-dd-HHmmss" )
).toString()
2012-11-07T12:16:03
java.time
The modern approach uses the java.time classes built into Java 8 and later. These classes are inherently thread-safe. These classes supplant the troublesome old legacy date-time classes that are un-thread-safe.
String input = "2012-11-07-121603" ;
DateTimeFormatter f = DateTimeFormatter.ofPattern( "uuu-MM-dd-HHmmss" ) ;
Parse as a LocalDateTime because your input lacks info about time zone or offset-from-UTC.
LocalDateTime ldt = LocalDateTime.parse( input , f );
ldt.toString(): 2012-11-07T12:16:03
Thread-safety
The java.time classes are designed to be thread-safe. The classes use immutable objects. You may cache objects such as DateTimeFormatter for re-use throughout your code and across threads.
ISO 8601
When serializing date-time values to text, use standard ISO 8601 formats only. Do not invent your own formats such as that shown in your Question. The standard formats are practical and sensible. They are designed to be easy to parse by machine yet easy to read by humans across cultures.
The java.time classes use ISO 8601 formats by default when parsing/generating strings. Example shown above.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

SimpleDateFormat fails to reject input missing century on the year of the input, despite "yyyy" in the formatting pattern

I have a SimpleDateFormat with the pattern yyyy-M-d", and the following scenario:
String str = "02-03-04";
SimpleDateFormat f = new SimpleDateFormat("yyyy-M-d");
f.setLenient(false);
System.out.println(f.parse(str));
The output is Sat Mar 04 00:00:00 EST 2
My goal was to only catch dates in the format like 2004-02-03 and to ignore 02-03-04. I thought the yyyy in the pattern would require a 4 digit year, but clearly this is not the case. Can anyone explain why this is not throwing a parse exception? I would like it to...
Well, I can explain it from the docs:
For parsing, if the number of pattern letters is more than 2, the year is interpreted literally, regardless of the number of digits. So using the pattern "MM/dd/yyyy", "01/11/12" parses to Jan 11, 12 A.D.
It's possible that Joda Time would be stricter - and it's a better API in general, IMO...
You could always throw an exception if the year is less than 1000 after parsing...
tl;dr
Using java.time, that input with that formatting pattern fails, just as you expected.
LocalDate
.parse(
"02-03-04" ,
DateTimeFormatter.ofPattern ( "uuuu-M-d" )
)
…throws java.time.format.DateTimeParseException
java.time
The classes you were using are now supplanted by the modern java.time classes defined in JSR 310 and built into Java 8 and later.
The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.
Define a custom formatting pattern as you asked. Use the DateTimeFormatter class.
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "uuuu-M-d" );
Try to parse your input.
String input = "02-03-04";
LocalDate localDate = LocalDate.parse ( input , f );
We encounter a DateTimeParseException, failing on the missing century of the year of the input. Just as you expected.
Exception in thread "main" java.time.format.DateTimeParseException: Text '02-03-04' could not be parsed at index 0
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Categories

Resources