java代码规范: JDK8 的应用,可以使用 Instant 代替 Date,LocalDateTime 代替 Calendar, DateTimeFormatter 代替 SimpleDateFormat(能保证线程安全),官方给出的解释:simple beautiful strong immutable thread-safe。 show code 需要修正为北京时间: Instant now= Instant.now().plusMillis(TimeUnit.HOURS.toMillis(8)); S...
This class is immutable and thread-safe. Since: 1.8 Field Summary Fields Modifier and TypeFieldDescription staticDateTimeFormatterBASIC_ISO_DATE The ISO date formatter that formats or parses a date without an offset, such as '20111203'.
1.使用ThreadLocal让每个线程都持有一个SimpleDateFormat实例,这样就不会争抢了; 2.使用Java8的DateTimeFormatter。 【代码示例】 packagecom.hy.lab.thsafedateformat;importjava.text.SimpleDateFormat;importjava.time.LocalDateTime;importjava.time.format.DateTimeFormatter;importjava.util.Date;publicclassDateUtil {/...
format(Date date, DateTimeFormatter formatter) formatter 可以选择已定义好的formatter比如YYYY_MM_DD_HH_MM_SS_FMT(yyyy-MM-dd HH:mm:ss)格式化日期。 (2)解析方法, parse*, 比如parseDateStrToDate(String text) 解析日期yyyy-MM-dd,返回Date; parseToDate(String text, DateTimeFormatter formatter) 根据 fo...
DateTimeFormatter的javadoc上写的很直白:This class is immutable and thread-safe.(这个类是不可变的,并且是线程安全的)。 同样,StringBuilder类里也明确写着:StringBuilder是一个可变的(mutable)字符序列。Instances of {@code StringBuilder} are not safe for use by multiple threads. If such synchronization is ...
import java.time.format.DateTimeFormatter; import java.time.temporal.TemporalAccessor; import java.time.temporal.TemporalField; import java.util.Objects; /** * 说明:localDate类研究 * @author carter * 创建时间: 2019年11月11日 15:31 **/
// 4. 使用DateTimeFormatter(This class is immutable and thread-safe.) DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); System.out.println(timeFormatter.format(LocalDateTime.now())); 5、有哪些设计模式?
DateTimeFormatter 代替 SimpleDateFormat,官方给出的解释:simple beautiful strong immutable thread-safe。 6.【强制】必须回收自定义的 ThreadLocal 变量,尤其在线程池场景下。 线程经常会被复用,如果不清理自定义的 ThreadLocal 变量,可能会影响后续业务逻辑和造成内存泄露等问题。
代码里使用 SimpleDateFormat 类的原因是因为日期使用了 Date 类,与 Date 相配套的 JDK 格式化类即 SimpleDateFormat 类,如果我们在处理日期时使用 JDK8 引入的 LocalDateTime 等不可变日期类,那么格式化将使用配套的线程安全的 DateTimeFormatter 类,从根源上规避掉对非线程安全类 SimpleDateFormat 类的使用。
The main date-time classes provide two methods - one for formatting,format(DateTimeFormatter formatter), and one for parsing,parse(CharSequence text, DateTimeFormatter formatter). For example: <blockquote> text/java复制 LocalDate date = LocalDate.now(); String text = date.format(formatter); Local...