CloudStack中云主机的UTC时间转为本地时间

× 文章目录
  1. 1. CloudStack UTC时间处理
    1. 1.1. 工具类①
    2. 1.2. 工具类②
    3. 1.3. 测试类

CloudStack UTC时间处理

CloudStack项目中使用的时间是UTC时间,具体什么是UTC时间大家可以百度,但是我们需要的时间是正常的时间,所以在国泰君安开发测试云中,同步资源管理中虚拟机的同步管理,需要对虚拟机的时间格式化进行转换。工具类如下,关键是时间格式的问题,时间格式为yyyy-MM-dd’T’HH:mm:ss+SSSS。

工具类①

1
2
3
4
5
6
7
8
9
10
11
12
13
public static Date utc2LocalDate(String utcTime) {
String utcTimePatten = "yyyy-MM-dd'T'HH:mm:ss+SSSS";
SimpleDateFormat sdf = new SimpleDateFormat(utcTimePatten);
Date dt = null;
try {
dt = sdf.parse(utcTime);
}
catch (ParseException e) {
e.printStackTrace();
}
return dt;
}

工具类②

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public class TestUtc {
public static void main(String args[]) {
try {
String ts = "2015-04-22T15:58:54+0800";
System.out.println("ts = " + ts);
ts = ts.replace("Z", " UTC");
System.out.println("ts = " + ts);
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss+SSSS");
Date dt = sdf.parse(ts);
TimeZone tz = sdf.getTimeZone();
Calendar c = sdf.getCalendar();
System.out.println("Display name: " + tz.getDisplayName());
System.out.println(getString(c));
}
catch (ParseException pe) {
System.out.println("Error offset: " + pe.getErrorOffset());
pe.printStackTrace();
}
}
private static String getString(Calendar c) {
StringBuffer result = new StringBuffer();
result.append(c.get(Calendar.YEAR));
result.append("-");
result.append((c.get(Calendar.MONTH) + 1));
result.append("-");
result.append(c.get(Calendar.DAY_OF_MONTH));
result.append(" ");
result.append(c.get(Calendar.HOUR_OF_DAY));
result.append(":");
result.append(c.get(Calendar.MINUTE));
result.append(":");
result.append(c.get(Calendar.SECOND));
return result.toString();
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class TestUtcTime {
/**
*
* @param args
* @return void
*/
public static void main(String[] args) {
String ts = "2015-04-22T15:58:54+0800";
Date date = new Date();
System.out.println(date);
System.out.println(DateUtil.utc2LocalDate(ts));
}
}
如果您觉得文章不错,可以打赏我喝一杯咖啡!