---
title: "Java自定义时间格式"
author: "deble_king"
date: "2015-08-05T09:33:57Z"
tags: []
categories: ["编程语言"]
slug: "java"
draft: false
lastmod: "2015-08-05T09:34:42Z"
id: 2232905
url: "https://deble.iteye.com/blog/2232905"
---

一、Java获取系统时间并转换为想要的格式

需要引进 java.util.Calendar 和 java.text.SimpleDateFormat 这两个类，

Calendar currentDate = Calendar.*getInstance*();

SimpleDateFormat sdf = **new** SimpleDateFormat("yyyyMMddhhmmss" );

String currentTime = sdf.format(currentDate.getTime());

System.***out***.println(currentTime);  
其中SimpleDateFormat格式化日期，可以对 new SimpleDateFormat("yyyyMMddhhmmss") 中引号里面的格式进行编辑,转换成自己相要的格式，比如还可以转换成new SimpleDateFormat("yyyy/MM/dd hh:mm:ss") 的格式等。

 

二、时间的单位转换

1秒=1000毫秒(ms) 1毫秒=1／1,000秒(s)  
1秒=1,000,000 微秒(μs) 1微秒=1／1,000,000秒(s)  
1秒=1,000,000,000 纳秒(ns) 1纳秒=1／1,000,000,000秒(s)  
1秒=1,000,000,000,000 皮秒(ps) 1皮秒=1／1,000,000,000,000秒(s)

1分钟=60秒  
1小时=60分钟=3600秒

 

三、System.currentTimeMillis()计算方式

1、System类代表系统，系统级的很多属性和控制方法都放置在该类的内部，该类位于java.lang包。  
currentTimeMillis方法  
public static long currentTimeMillis()  
该方法的作用是返回当前的计算机时间，时间的表达格式为当前计算机时间和GMT时间(格林威治时间)1970年1月1号0时0分0秒所差的毫秒数。  
可以直接把这个方法强制转换成date类型。  
代码如下：  
long currentTime = System.currentTimeMillis();//返回变量类型是long  
SimpleDateFormat formatter = new SimpleDateFormat("yyyy年-MM月dd日-HH时mm分ss秒");  
Date date = new Date(currentTime);  
System.out.println(formatter.format(date));  
运行结果如下：当前时间:2015年-08月04日-14时53分35秒

2、在开发过程中，通常很多人都习惯使用new Date()来获取当前时间。new Date()所做的事情其实就是调用了System.currentTimeMillis()。如果仅仅是需要或者毫秒数，那么完全可以使用System.currentTimeMillis()去代替new Date()，效率上会高一点。如果需要在同一个方法里面多次使用new Date()，通常性能就是这样一点一点地消耗掉，这里其实可以声明一个引用。

用法如下：

例：System.currentTimeMillis()+3600\*1000可以这样解读：System.currentTimeMillis()相当于是毫秒为单位，但是后头成了1000，就变成了以秒为单位。那么，3600秒=1小时，所以输出时间为当前时间的1小时后。

例：System.currentTimeMillis()+time\*1000，里面传入的time是以秒为单位，当传入60，**System.out.println(new Date(System.currentTimeMillis()+60\*1000))**

则输出时间：当前时间的一分钟后