本文目录一览:
java时间格式转换
实现思路就是先通过SimpleDateFormat方法定义一个时间类型的格式,之后SimpleDateFormat的format方法将一个符合时间格式的字符串匹配成对应的格式 举例:
String str0 = "2015年07月05日";
Date d1 = new SimpleDateFormat("yyyy年MM月dd日").parse(str0); //定义起始日期
SimpleDateFormat sdf0 = new SimpleDateFormat("yyyy"); //定义一个只有年份的
SimpleDateFormat sdf1 = new SimpleDateFormat("MM"); //月份的
SimpleDateFormat sdf2 = new SimpleDateFormat("dd"); //日的
String str1 = sdf0.format(d1); //取出特定日期d1的年份
String str2 = sdf1.format(d1); //取出特定日期d1的月份
String str3 = sdf2.format(d1); //取出特定日期d1的日
System.out.println("年份为:" + str1);
System.out.println("月份为:" + str2);
System.out.println("日为:" + str3);
java 时间格式的转换
public class myMain {
public static void main(String[] args) {
// 日历类
Calendar calendar = Calendar.getInstance(); // 实例化
int year = calendar.get(Calendar.YEAR); // 年
int mouth = calendar.get(Calendar.MONTH) + 1; // 月
int day = calendar.get(Calendar.DAY_OF_MONTH); // 几号
int hour = calendar.get(Calendar.HOUR); // 小时
int minute = calendar.get(Calendar.MINUTE); // 分
int second = calendar.get(Calendar.SECOND); // 秒
// 设置制定年月日
calendar.set(2014, 11, 1, 1, 1, 1);
year = calendar.get(Calendar.YEAR); // 年
mouth = calendar.get(Calendar.MONTH); // 月
day = calendar.get(Calendar.DAY_OF_MONTH); // 几号
hour = calendar.get(Calendar.HOUR); // 小时
minute = calendar.get(Calendar.MINUTE); // 分
second = calendar.get(Calendar.SECOND); // 秒
System.out.println(year + "=" + mouth + "=" + day + "=" + hour + "="
+ minute + "=" + second);
// 获取指定格式输出日期
Date date = new Date(); // 可以使用时间戳
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String riqi = dateFormat.format(date);
System.out.println(riqi);
// 获得2010年9月13日22点36分01秒 的Date对象
SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date myDate2 = null;
try {
myDate2 = dateFormat2.parse("2010-09-13 22:36:01");
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long myie = myDate2.getTime();
long myief = 1284388561000L; //后面必须有个L
String rename = dateFormat2.format(new Date(myief));
}
}
在java中如何将12小时制的时间转换为24小时制
Java中将12小时制的时间转换为24小时制的方式如下:
import java.text.SimpleDateFormat;
import java.util.Date;
public class ceshi {
public static void main(String[] args) {
SimpleDateFormat objSDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //转换为24小时制
String strCurrentTime = objSDateFormat.format(new Date());
System.out.println(strCurrentTime);
}
}
注:大写的HH
为24小时制,小写的hh
为12小时制,当然还可以在ss
的后面加上 a
,这样可以在后面显示上下文:显示效果为“2008-03-24 17:00:14 下午”
运行结果为: