Java:simpledateformat using the Notes

Source: Internet
Author: User
Tags dateformat

Preface : In Java, speaking of date conversion, SimpleDateFormat have to mention, but in combat operations, use should be careful. Otherwise there will be a "java.lang.NumberFormatException:multiple points" error, so what exactly is it?

first , let's take a look at a date conversion class that uses SimpleDateFormat.

 PackageCom.mwq.format;ImportJava.text.ParseException;ImportJava.text.SimpleDateFormat;ImportJava.util.Date; Public  class dateutils {    /** * YYYY-MM-DD Formatter * *    Private Static FinalSimpleDateFormat Ymd_dash_formatter =NewSimpleDateFormat ("Yyyy-mm-dd"); Public Static Long Gettimemillisspecifydaysbaseontoday(intDays) {LongMillis =0LTry{Date Datetomorrow =NewDate (); String tomorrow = Ymd_dash_formatter.format (Datetomorrow);//System.out.println (tomorrow);Date tomorrownew = Ymd_dash_formatter.parse (Tomorrow);        Millis = Tomorrownew.gettime (); }Catch(ParseException e) {        }returnMillis; }}

The content is simple, statically initializes a simpledateformat, and then uses it to convert a wee time stamp, using the SimpleDateFormat format and parse method.
The class seems to be fine, but I didn't find any reason to prove it was a problem! (Small series of programming level is limited AH!) )

Next , we write a test class call.

 PackageCom.mwq.format; Public  class Test {     Public Static void Main(string[] args) { for(inti =0; I <Ten; i++) {Thread Thread1 =NewThread () { Public void Run() {System.out.println (Dateutils.gettimemillisspecifydaysbaseontoday (0));            }            };        Thread1.start (); }    }}

Main class Loop 10 that's all, creating threads to invoke the Gettimemillisspecifydaysbaseontoday method, and that's it.

then , let's take a look at the results.

1436544000000143654400000083520000014365440000001436544000000835200000Exception in Thread"Thread-2"Java.lang.NumberFormatException:multiple points at Sun.misc.FloatingDecimal.readJavaFormatString ( Floatingdecimal.java:1084) at Java.lang.Double.parseDouble (Double.java:510) at Java.text.DigitList.getDouble (Digitlist.java:151) at Java.text.DecimalFormat.parse (Decimalformat.java:1303) at Java.text.SimpleDateFormat.subParse (Simpledateformat.java:1538) at Java.text.SimpleDateFormat.parse (Simpledateformat.java:1263) at Java.text.DateFormat.parse (Dateformat.java:335) at Com.mwq.format.DateUtils.getTimeMillisSpecifyDaysBaseOnToday (Dateutils.java: -) at com.mwq.format.test$1.Run (Test.java:Ten) Exception in thread"Thread-9"Java.lang.NumberFormatException:multiple points1436544000000At Sun.misc.FloatingDecimal.readJavaFormatString (Floatingdecimal.java:1084) at Java.lang.Double.parseDouble (Double.java:510) at Java.text.DigitList.getDouble (Digitlist.java:151) at Java.text.DecimalFormat.parse (Decimalformat.java:1303) at Java.text.SimpleDateFormat.subParse (Simpledateformat.java:1538) at Java.text.SimpleDateFormat.parse (Simpledateformat.java:1263) at Java.text.DateFormat.parse (Dateformat.java:335)1436544000000At Com.mwq.format.DateUtils.getTimeMillisSpecifyDaysBaseOnToday (Dateutils.java: -) at com.mwq.format.test$1.Run (Test.java:Ten)

What the? Output a big push error!

Take a look at the source code!

    /** * Returns a new <code>double</code> initialized to the value * represented by the specified &L T;code>string</code>, as performed * by the <code>valueOf</code> method of class * <CODE&G     T;double</code>.     * * @param s The string to be parsed.     * @return The <code>double</code> value represented by the string * argument. * @exception numberformatexception If the string does not contain * a parsable <code>double&     Lt;/code>. * @see java.lang.double#valueof (String) * @since 1.2 */     Public Static Double parsedouble(String s)throwsNumberFormatException {returnFloatingdecimal.readjavaformatstring (s). Doublevalue (); }

If the string does not contain a convertible double, then the numberformatexception exception is thrown.
Of course, there seems to be no explanation for the error.

so , let's take a look at SimpleDateFormat's API Doc explanation.

Parsepublic Date Parse (String text,                  thrown: nullpointerexception-if text or POS is null.) See also: Dateformat.setlenient (Boolean)

In other words, String tomorrow = YMD_DASH_FORMATTER.format(dateTomorrow);
// System.out.println(tomorrow);
Date tomorrownew = YMD_DASH_FORMATTER.parse(tomorrow);

A null pointer reference was generated.

In fact , looking back at our log information, we can actually find some clues.

835200000
1436544000000
1436544000000
835200000

If everything is normal, should be output "1436544000000" Only right, why appeared "835200000"?
Look again.

This method attempts to parse the text that begins at the given index of the Pos. If the resolution succeeds, the index of the POS is updated to the index after the last character used (it is not necessary to parse all characters until the end of the string), and returns the parsed date. The updated POS can be used to indicate the starting point of the next call to this method. If an error occurs, the index of the POS is not changed, and the error index of the POS is set to the character index at which the error occurred, and NULL is returned.

This passage, you may have suddenly dawned, in the multi-threaded concurrency situation, SimpleDateFormat is obviously not safe enough !
Of course, this explanation was invented by me!

so , how to avoid such a mistake?
1.DateUtils class in the Gettimemillisspecifydaysbaseontoday method to print a tomorrow, or a random output of something just fine.

 PackageCom.mwq.format;ImportJava.text.ParseException;ImportJava.text.SimpleDateFormat;ImportJava.util.Date; Public  class dateutils {    /** * YYYY-MM-DD Formatter * *    Private Static FinalSimpleDateFormat Ymd_dash_formatter =NewSimpleDateFormat ("Yyyy-mm-dd"); Public Static Long Gettimemillisspecifydaysbaseontoday(intDays) {LongMillis =0LTry{Date Datetomorrow =NewDate ();            String tomorrow = Ymd_dash_formatter.format (Datetomorrow); System.out.println (Tomorrow);//System.out.println ("111111111111");Date tomorrownew = Ymd_dash_formatter.parse (Tomorrow);        Millis = Tomorrownew.gettime (); }Catch(ParseException e) {        }returnMillis; }}

The Ymd_dash_formatter in the 2.DateUtils class put the wrong position and replace it with the following words, there will be no problem.

 PackageCom.mwq.format;ImportJava.text.ParseException;ImportJava.text.SimpleDateFormat;ImportJava.util.Date; Public  class dateutils {    /** * YYYY-MM-DD Formatter * *     Public Static Long Gettimemillisspecifydaysbaseontoday(intDays) {LongMillis =0LTry{SimpleDateFormat Ymd_dash_formatter =NewSimpleDateFormat ("Yyyy-mm-dd"); Date Datetomorrow =NewDate (); String tomorrow = Ymd_dash_formatter.format (Datetomorrow);//System.out.println (tomorrow);//System.out.println ("");Date tomorrownew = Ymd_dash_formatter.parse (Tomorrow);        Millis = Tomorrownew.gettime (); }Catch(ParseException e) {        }returnMillis; }}

Summary : In fact this time, I do not know what to say? One because I have never been to Java, two because if not read "effective Java", want to use the above ideas to apply to the project caused by the error will not have these rhetoric, but encounter problems to explore is always good.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Java:simpledateformat using the Notes

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.