package com.base.core.utiles;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

/**
 * <p>Description:时间字符串转换</p>
 * <p>Copyright: Copyright (c) 2009</p>
 * <p>Company:航天恒星科技有限公司软件中心</p>
 * @author 孙晓良
 */
public class DateFormatter {
	
	/**
	 * 将YYYY-MM-DD HH:MM:SS.SSS的字符串变为类型为Calendar的日期
	 * @param str_Time String 字符串表示的时间
	 * @return Calendar Calendar类型的时间
	 */
	public static Calendar stringtoCalendar(String str_Time) {
		try {
			int year = Integer.parseInt(str_Time.substring(0, 4));
			int month = Integer.parseInt(str_Time.substring(5, 7));
			int day = Integer.parseInt(str_Time.substring(8, 10));
			int hour = Integer.parseInt(str_Time.substring(11, 13));
			int minute = Integer.parseInt(str_Time.substring(14, 16));
			int second = Integer.parseInt(str_Time.substring(17, 19));
			Calendar time = new GregorianCalendar(year, month - 1, day, hour, minute, second);
			return time;
		} catch (NumberFormatException e) {
			return null;
		}
	}
	

	public static String string2Timezone(String srcFormater,
					String srcDateTime, String srcTimeZoneId, String dstFormater,
					String dstTimeZoneId) {
		if (srcFormater == null || "".equals(srcFormater))
			return null;
		if (srcDateTime == null || "".equals(srcDateTime))
			return null;
		if (dstFormater == null || "".equals(dstFormater))
			return null;
		if (dstTimeZoneId == null || "".equals(dstTimeZoneId))
			return null;
		SimpleDateFormat sdf = new SimpleDateFormat(srcFormater);
		try {
			int diffTime = getDiffTimeZoneRawOffset(srcTimeZoneId,
					dstTimeZoneId);
			Date d = sdf.parse(srcDateTime);
			long nowTime = d.getTime();
			long newNowTime = nowTime - diffTime;
			d = new Date(newNowTime);
			return date2String(dstFormater, d);
		} catch (ParseException e) {
			return null;
		} finally {
			sdf = null;
		}
	}  
	     
	private static int getDiffTimeZoneRawOffset(String srcTimeZoneID,
						String timeZoneId) {
		return TimeZone.getTimeZone(srcTimeZoneID).getRawOffset()
				- TimeZone.getTimeZone(timeZoneId).getRawOffset();
	}

	public static String date2String(String formater, Date aDate) {
		if (formater == null || "".equals(formater))
			return null;
		if (aDate == null)
			return null;
		return (new SimpleDateFormat(formater)).format(aDate);
	}

	public static String string2TimezoneDefault(String srcDateTime,
					String srcTimeZoneId, String dstTimeZoneId) {
		return string2Timezone("yyyy-MM-dd HH:mm:ss.SSS", srcDateTime,
				srcTimeZoneId, "yyyy-MM-dd HH:mm:ss.SSS", dstTimeZoneId);
	} 
	
	public static String srcTimePattern2DstTimePattern(String srcTime,TimePattern  srcTimePattern,TimePattern dstTimePattern)
	{
		return DateFormatter.string2Timezone(srcTimePattern.getTimeformat(),srcTime,srcTimePattern.getTimezoneId(),dstTimePattern.getTimeformat(),dstTimePattern.getTimezoneId());
	}
}