The problem of time conversion Long

SimpleDateFormat format = new SimpleDateFormat(pattern); obtains the default time zone of the current device (such as the East Eighth District of Beijing time),
And format.parse(strTime).getTime(); To get the long time of strTime, it will treat strTime as the East Eighth District and then convert it to Universal Time (UTC) and then calculate the number of milliseconds.
For example: pattern is: HH:mm format, strTime:01:06.
And the milliseconds of 1970-01-01 00:00:00 in Universal Time (UTC) is 0. At this time, 01:06 is added to 1970-01-01 by default, that is, 1970-01-01 01:06 is regarded as East Eight zone time, then turn
UTC time becomes 1969-12-31 17:06 to calculate, the result is a negative number.

Solution:
/**
 * Convert to String time in pattern format according to the milliseconds of world time
 * @param pattern
 * @param utcTimeMillis world time in milliseconds
 * @return
 */
public static String formatByUTCTimeMillis(String pattern,long utcTimeMillis)
{
	if (!StringUtil.isEmpty(pattern))
	{
		try
		{
			Date d = new Date(utcTimeMillis);
			SimpleDateFormat format = new SimpleDateFormat(pattern);
			format.setTimeZone(TimeZone.getTimeZone("UTC"));
			return format.format(d);
		} catch (Exception e)
		{
			String msg = "formatByUTCTimeMillis(pattern:" + pattern + ",longTime:" + utcTimeMillis + ")";
			Logger.e2s(new Exception(msg,e));
		}
	}
	return null;
}

/**
 * Convert the string time of the world time to the millisecond time of the world time
 * @param pattern strTime date format
 * @param utcStrTime world time pattern format String time
 * @return
 */
public static long formatByUTCStrTime(String pattern,String utcStrTime)
{
	if(!StringUtil.isEmpty(pattern) && !StringUtil.isEmpty(utcStrTime))
	{
		try
		{
			SimpleDateFormat format = new SimpleDateFormat(pattern);
			format.setTimeZone(TimeZone.getTimeZone("UTC"));
			return format.parse(utcStrTime).getTime();
		} catch (Exception e)
		{
			String msg = "formatByUTCStrTime(pattern:"+pattern+",strTime:"+utcStrTime+")";
			Logger.e2s(new Exception(msg,e));
		}
	}
	
	return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326968388&siteId=291194637