Java: SimpleDateFormat

Source: Internet
Author: User
Tags dateformat pos index

Java: SimpleDateFormat

Preface: In Java, SimpleDateFormat has to be mentioned for date conversion, but be careful when using it in practice. Otherwise, the error "java. lang. NumberFormatException: multiple points" will occur. Why?

FirstTo see a date conversion class that uses SimpleDateFormat.

package com.mwq.format;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateUtils {    /**     * yyyy-MM-dd formatter     */    private static final SimpleDateFormat YMD_DASH_FORMATTER = new SimpleDateFormat(yyyy-MM-dd);    public static long getTimeMillisSpecifyDaysBaseOnToday(int days) {        long millis = 0l;        try {            Date dateTomorrow = new Date();            String tomorrow = YMD_DASH_FORMATTER.format(dateTomorrow);//          System.out.println(tomorrow);            Date tomorrownew = YMD_DASH_FORMATTER.parse(tomorrow);            millis = tomorrownew.getTime();        } catch (ParseException e) {        }        return millis;    }}

The content is very simple. initialize a SimpleDateFormat statically and use it to convert a timestamp in the early morning. The SimpleDateFormat format and parse methods are used.
The class seems to be okay. I didn't find any reason to prove it was wrong! (The programming level of xiaobian is limited !)

Second, Let's write a test class to call it.

package com.mwq.format;public class Test {    public static void main(String[] args) {        for (int i = 0; i < 10; i++) {            Thread thread1 = new Thread() {                public void run() {                    System.out.println(DateUtils.getTimeMillisSpecifyDaysBaseOnToday(0));                }            };            thread1.start();        }    }}

The main class loops 10. This is the only way to create a thread to call the getTimeMillisSpecifyDaysBaseOnToday method.

ThenLet'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:20)    at com.mwq.format.Test$1.run(Test.java:10)Exception in thread Thread-9 java.lang.NumberFormatException: multiple points1436544000000    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)1436544000000    at com.mwq.format.DateUtils.getTimeMillisSpecifyDaysBaseOnToday(DateUtils.java:20)    at com.mwq.format.Test$1.run(Test.java:10)

What? A big push error is output!

ViewLet's look at the source code!

    /**     * Returns a new double initialized to the value     * represented by the specified String, as performed     * by the valueOf method of class     * Double.     *     * @param      s   the string to be parsed.     * @return the double value represented by the string     *         argument.     * @exception NumberFormatException if the string does not contain     *            a parsable double.     * @see        java.lang.Double#valueOf(String)     * @since 1.2     */    public static double parseDouble(String s) throws NumberFormatException {    return FloatingDecimal.readJavaFormatString(s).doubleValue();    }

If the string does not contain a convertible double, a NumberFormatException is thrown.
Of course, there seems to be no good explanation for the above errors.

SoLet's take a look at the API doc explanation of SimpleDateFormat.

Parsepublic Date parse (String text, ParsePosition pos) parses the String text to generate a Date. This method tries to parse the text starting from the index given by the pos. If the resolution is successful, the pos index is updated to the index after the last character used (you do not have to parse all the characters until the end of the string), and the parsed date is returned. The updated pos can be used to indicate the starting point of the next call to this method. If an error occurs, the pos index is not changed, and the pos index is set to the character index where the error occurs, and null is returned. The parse parameter in the DateFormat class: text-should parse some of the strings. Pos-A ParsePosition object with the index and error index information described above. Returns the Date parsed from the string. If an error occurs, null is returned.Throw: NullPointerException-If text or pos is null.For more information, see DateFormat. setLenient (boolean)

That is to say,String tomorrow = YMD_DASH_FORMATTER.format(dateTomorrow);
// System.out.println(tomorrow);
Date tomorrownew = YMD_DASH_FORMATTER.parse(tomorrow);

A null pointer reference is generated.

ActuallyAnd then look back at our log information. We can actually find some clues.

835200000
1436544000000
1436544000000
835200000

If everything is normal, you should output"1436544000000"That's right. Why does it appear?"835200000"?
Let's take a look.

This method tries to parse the text starting from the index given by the pos. If the resolution is successful, the pos index is updated to the index after the last character used (you do not have to parse all the characters until the end of the string), and the parsed date is returned. The updated pos can be used to indicate the starting point of the next call to this method. If an error occurs, the pos index is not changed, and the pos index is set to the character index where the error occurs, and null is returned.

In this paragraph, you may have suddenly realized,SimpleDateFormat is not safe enough in the case of multi-thread concurrency.!
Of course, this is an explanation I wrote!

SoHow can we avoid such errors?
1. Print tomorrow in the getTimeMillisSpecifyDaysBaseOnToday method of the DateUtils class, or simply output something.

package com.mwq.format;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateUtils {    /**     * yyyy-MM-dd formatter     */    private static final SimpleDateFormat YMD_DASH_FORMATTER = new SimpleDateFormat(yyyy-MM-dd);    public static long getTimeMillisSpecifyDaysBaseOnToday(int days) {        long millis = 0l;        try {            Date dateTomorrow = new Date();            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) {        }        return millis;    }}

2. The YMD_DASH_FORMATTER in the DateUtils class puts the wrong location. If you change it to the following, the problem will not occur.

package com.mwq.format;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class DateUtils {    /**     * yyyy-MM-dd formatter     */    public static long getTimeMillisSpecifyDaysBaseOnToday(int days) {        long millis = 0l;        try {            SimpleDateFormat YMD_DASH_FORMATTER = new SimpleDateFormat(yyyy-MM-dd);            Date dateTomorrow = new Date();            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) {        }        return millis;    }}

Summary: Actually, I don't know what to say at this time? First, because I have never been familiar with Java, and second, if I do not read objective Java, I want to use the above ideas to apply them to the project, and there will be no such comments, but it is good to explore the problems.

 

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.