/*
* Copyright (c) 2009, 2010, 2011, 2012, 2013 tinygao
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jdk.date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.lang.StringUtils;
/**
* @author tingao
* 2013-1-5
*/
public final class DateUtils {
private static Logger log = Logger.getLogger(DateUtils.class.getName());
private static ThreadLocal<DateFormat> timeMap = new ThreadLocal<DateFormat>();
private static final String dateFormat = "yyyy-MM-dd hh:mm:ss";
/**
* 将时间转换成一定格式的日期字符串
* 如果dateFromat为空,就按照默认的格式输出
* @param date 日期
* @param dateFormat 转成字符串日期格式
* @return dateFormt格式的日期
* 2013-1-5 上午11:04:03
*/
public static String formatDate(Date date, String dateFormat) {
if(StringUtils.isEmpty(dateFormat)) {
dateFormat = DateUtils.dateFormat;
}
String result = "";
DateFormat dt = instanceDateFormat(dateFormat);
result = dt.format(date);
return result;
}
/**
* @param str
* @param dateFormat
* @return
* 2013-1-5 上午11:06:26
*/
public static Date parse(String str, String dateFormat) {
if(StringUtils.isEmpty(dateFormat)) {
dateFormat = DateUtils.dateFormat;
}
try {
DateFormat dt = instanceDateFormat(dateFormat);
return dt.parse(str);
} catch (ParseException e) {
log.log(Level.SEVERE, "从字符串转时间出错,详情:"+e.toString());
}
return null;
}
public static Date parse(String str) {
return parse(str, null);
}
public static String formatDate(Date date) {
return formatDate(date, null);
}
private static DateFormat instanceDateFormat(String dateFormat) {
DateFormat dt = timeMap.get();
if(dt == null) {
dt = new SimpleDateFormat(dateFormat);
timeMap.set(dt);
}
return dt;
}
//test
/*static class ThreadA implements Runnable {
int i = 0;
@Override
public void run() {
while(i++ < 100) {
String date = formatDate(new Date(), "yyyy-MM-dd");
System.out.println("线程A"+i+":" + date);
}
}
}
static class ThreadB implements Runnable {
int i = 0;
@Override
public void run() {
while(i++ < 100) {
String date = formatDate(new Date(), "yyyy-MM-dd hh:mm");
System.out.println("线程B"+i+":" + date);
}
}
}
public static void main(String[] args) {
String str = formatDate(new Date());
System.out.println(str);
Date date = parse("2013-01-05 11:11:16");
System.out.println(date);
ThreadA threadA = new ThreadA();
Thread tha = new Thread(threadA);
tha.start();
ThreadB threadB = new ThreadB();
Thread thb = new Thread(threadB);
thb.start();
}*/
}