DateTimeFormatter与SimpleDateFormat

日期格式化类:DateTimeFormatter与SimpleDateFormat

一、SimpleDateFormat类

  1. SimpleDateFormat是用于以对语言环境敏感的方式格式化和解析日期的具体类。
  2. SimpleDateFormat类的构造方法
NO 构造器 描述
1 SimpleDateFormat() SimpleDateFormat使用默认FORMAT语言环境的默认模式和日期格式符号 构造一个。
2 SimpleDateFormat​(Stringpattern) SimpleDateFormat使用给定的模式和默认FORMAT语言环境的默认日期格式符号 构造一个。
3 SimpleDateFormat​(Stringpattern,DateFormatSymbolsformatSymbols) SimpleDateFormat使用给定的模式和日期格式符号构造一个。
4 SimpleDateFormat​(Stringpattern,Localelocale) SimpleDateFormat使用给定语言环境和给定语言环境的默认日期格式符号构造一个。
SimpleDateFormat为什么不是线程安全的?
  1. SimpleDateFormat类的方法没有使用synchronized来给共享变量加锁。
  2. SimpleDateFormat继承于DateFormat,下面我们看看我们用来格式化的format()方法的部分源码
  • DateFormat.java
    public final String format(Date date)
    {
        return format(date, new StringBuffer(),
                      DontCareFieldPosition.INSTANCE).toString();
    }

    public abstract StringBuffer format(Date date, StringBuffer toAppendTo,
                                        FieldPosition fieldPosition);
  • SimpleDateFormat.java
    @Override
    public StringBuffer format(Date date, StringBuffer toAppendTo,
                               FieldPosition pos)
    {
    //  如此轻易地使用内部变量,肯定不能线程安全
    //  线程都对pos进行写操作,必然会影响其他线程的读操作
        pos.beginIndex = pos.endIndex = 0;
        return format(date, toAppendTo, pos.getFieldDelegate());
    }

    private StringBuffer format(Date date, StringBuffer toAppendTo,
                                FieldDelegate delegate) {
        // Convert input date to time field list
       // 这里已经彻底毁坏线程的安全性
        calendar.setTime(date);

        boolean useDateFormatSymbols = useDateFormatSymbols();

        for (int i = 0; i < compiledPattern.length; ) {
            int tag = compiledPattern[i] >>> 8;
            int count = compiledPattern[i++] & 0xff;
            if (count == 255) {
                count = compiledPattern[i++] << 16;
                count |= compiledPattern[i++];
            }

            switch (tag) {
            case TAG_QUOTE_ASCII_CHAR:
                toAppendTo.append((char)count);
                break;

            case TAG_QUOTE_CHARS:
                toAppendTo.append(compiledPattern, i, count);
                i += count;
                break;

            default:
                subFormat(tag, count, delegate, toAppendTo, useDateFormatSymbols);
                break;
            }
        }
        return toAppendTo;
    }

看源码不用全部看,只需要看重点,不然你会很难受,很耗费时间。SimpleDateFormat类中的format方法的一段代码calendar.setTime(date);,从这我们可以看出来,如果我们把SimpleDateFormat定义成static成员变量,那么多个thread之间会共享这个SimpleDateFormat对象, 所以Calendar对象也会被共享。那么当有线程A,B操作该方法时,A线程已经给Calendar对象setTime了,但是这时A线程让出了cpu被B线程抢占了,这时B线程在给Calendar对象setTime一个值,然后A线程获得cpu处理,这时A线程以为使用的是它给setTime的值,其实这里的值已经被B线程更改了。这里就会出现线程不安全,因为这里的处理对象都被两个或者更多的线程公用,就会出现线程不安全,所以我们在开发时,尽量使用内部变量,不共享的变量。 3. 实例

package www.com.lining.dateformate;

import java.text.SimpleDateFormat;
import java.util.Locale;

public class DateTimeFormateTest1 {

	private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
	private static String date[] = { "01-Jan-1999", "09-Jan-2000", "08-Jan-2001", "07-Jan-2002", "06-Jan-2003",
			"05-Jan-2004", "04-Jan-2005", "03-Jan-2006", "02-Jan-2007" };

	public static void main(String[] args) {
		for (int i = 0; i < date.length; i++) {
			final int temp = i;
			new Thread(new Runnable() {
				@Override
				public void run() {
					try {
						while (true) {
							String str1 = date[temp];
							String str2 = sdf.format(sdf.parse(str1));
							System.out.println(Thread.currentThread().getName() + ", " + str1 + "," + str2);
							if (!str1.equals(str2)) {
								throw new RuntimeException(
										Thread.currentThread().getName() + ", Expected " + str1 + " but got " + str2);
							}
						}
					} catch (Exception e) {
						throw new RuntimeException("parse failed", e);
					}
				}
			}).start();
		}
	}
}

  1. 输出
  2. 一定要注意cpu的使用权都是需要去抢占的,所以就会出现多线程情况下,出现线程安全问题。
SimpleDateFormat线程不安全的解决方法
  1. 将SimpleDateFormat定义成局部变量,每次使用时在new 对象。但是每调用一次方法就会创建一个SimpleDateFormat对象,方法结束又要作为垃圾回收,很浪费资源。
  2. 加一把线程同步锁:synchronized(lock)
public class SyncDateFormatTest {
    private static SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
    private static String date[] = { "01-Jan-1999", "01-Jan-2000", "01-Jan-2001" };
 
    public static void main(String[] args) {
        for (int i = 0; i < date.length; i++) {
            final int temp = i;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            synchronized (sdf) {
                                String str1 = date[temp];
                                Date date = sdf.parse(str1);
                                String str2 = sdf.format(date);
                                System.out.println(Thread.currentThread().getName() + ", " + str1 + "," + str2);
                                if(!str1.equals(str2)){
                                    throw new RuntimeException(Thread.currentThread().getName() 
                                            + ", Expected " + str1 + " but got " + str2);
                                }
                            }
                        }
                    } catch (Exception e) {
                        throw new RuntimeException("parse failed", e);
                    }
                }
            }).start();
        }
    }
}

缺点是:每次都要等该锁释放其他的线程才能使用,性能差。 3. 使用ThreadLocal类

  • 直接继承与Object类,该类提供了线程局部变量,这些变量不同于他们的普通对应物,因为访问某个变量的每个线程都有自己的局部变量,它独立于变量的初始化副本。
  • 每个线程都将拥有自己的SimpleDateFormat对象副本。
public class DateUtil {
 private static ThreadLocal<SimpleDateFormat> local = new ThreadLocal<SimpleDateFormat>();

 public static Date parse(String str) throws Exception {
     SimpleDateFormat sdf = local.get();
     if (sdf == null) {
         sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
         local.set(sdf);
     }
     return sdf.parse(str);
 }
 
 public static String format(Date date) throws Exception {
     SimpleDateFormat sdf = local.get();
     if (sdf == null) {
         sdf = new SimpleDateFormat("dd-MMM-yyyy", Locale.US);
         local.set(sdf);
     }
     return sdf.format(date);
 }
}
public class ThreadLocalDateFormatTest {
 private static String date[] = { "01-Jan-1999", "01-Jan-2000", "01-Jan-2001" };

 public static void main(String[] args) {
     for (int i = 0; i < date.length; i++) {
         final int temp = i;
         new Thread(new Runnable() {
             @Override
             public void run() {
                 try {
                     while (true) {
                         String str1 = date[temp];
                         Date date = DateUtil.parse(str1);
                         String str2 = DateUtil.format(date);
                         System.out.println(str1 + "," + str2);
                         if(!str1.equals(str2)){
                             throw new RuntimeException(Thread.currentThread().getName() 
                                     + ", Expected " + str1 + " but got " + str2);
                         }
                     }
                 } catch (Exception e) {
                     throw new RuntimeException("parse failed", e);
                 }
             }
         }).start();
     }
 }
 } 

这样每个线程都有自己的副本对象SimpleDateFormat,所以每次不同的线程调用的都是自己的副本对象,不会改变其他线程的对象的。

二、DateTimeFormatter类

  1. jdk1.8中新增了 LocalDate 与 LocalDateTime等类来解决日期处理方法,同时引入了一个新的类DateTimeFormatter来解决日期格式化问题。
  2. LocalDateTime,DateTimeFormatter两个类都没有线程问题,只要你自己不把它们创建为共享变量就没有线程问题。
  3. 可以使用Instant代替 Date,LocalDateTime代替 Calendar,DateTimeFormatter 代替 SimpleDateFormat。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
LocalDate date = LocalDate.parse("2017 06 17", formatter);
System.out.println(formatter.format(date));
  1. DateTimeFormatter.ofPattern(pattern)的实现
 public static DateTimeFormatter ofPattern(String pattern) {
        return new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter();
    }

public final class DateTimeFormatterBuilder extends Object
  • TimeFormatterBuilder():用于创建日期时间格式化程序的生成器。
  • TimeFormatterBuilder().appendPattern(pattern):将指定模式定义的元素追加到构建器,返回TimeFormatterBuilder对象。
  • toFormatter():通过DateTimeFormatter使用默认语言环境创建来完成此构建器,获取DateTimeFormatter对象。
  • 模式基于字母和符号的简单序列。模式用于使用ofPattern(String)和ofPattern(String, Locale)方法创建格式化程序 。例如, "d MMM uuuu"将2011-12-03的格式设置为“ 2011年12月3日”。从模式创建的格式化程序可以根据需要多次使用,它是不可变的并且是线程安全的。 例如:
LocalDate日期= LocalDate.now();
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(“ yyyy MM dd”);
字符串文本= date.format(formatter);
LocalDate parsedDate = LocalDate.parse(text,formatter);
  1. 其中的LocalDate和LocalDateTime都可以去查看jdk1.8往上的版本api去学习。