java菜鸟教程(java时间操作)

精英怪
广告

java操作时间的方式

java菜鸟教程(java时间操作)

获取年月日时分秒

public class Test { public static void main(String[] args) { System.out.println("----------使用Calendar--------------------"); Calendar cal = Calendar.getInstance(); System.out.println("年"+cal.get(Calendar.YEAR)); System.out.println("月"+(cal.get(Calendar.MONTH)+1)); // Calendar.MONTH 获取到的是0-11 System.out.println("日"+cal.get(Calendar.DATE)); System.out.println(cal.get(Calendar.HOUR)); // 12小时制的小时 System.out.println("时"+cal.get(Calendar.HOUR_OF_DAY)); // 24小时制的小时 System.out.println("分"+cal.get(Calendar.MINUTE)); System.out.println("秒"+cal.get(Calendar.SECOND)); System.out.println("--------------使用java8的LocalDateTime----------------"); LocalDateTime local = LocalDateTime.now(); System.out.println("年"+local.getYear()); System.out.println(local.getMonth().name()); // 英文的月 System.out.println("月"+local.getMonthValue()); // 阿拉伯数字 相当于local.getMonth().getValue() System.out.println("日"+local.getDayOfMonth()); System.out.println("时"+local.getHour()); // 24小时制的小时 System.out.println("分"+local.getMinute()); System.out.println("秒"+local.getSecond()); } }

时间格式化中的字符含义

字符

描述

G

时代指示器(AD)

y

年(2001)

M

月(07)

d

天(20)

h

带有A.M./P.M.的小时(1~12)

H

小时(0~23)

m

分钟(0~59)

s

秒(0~59)

S

毫秒

E

周几(星期四)

D

一年中的第几天

w

一年中的第几周

W

一月中的第几周

a

A.M./P.M.标记

k

一天中的第几个小时(1~24)

K

带有A.M./P.M.的小时

z

时区

DateFormat format = new SimpleDateFormat("yyyy.MM.dd E"); //2021.01.14 星期四 System.out.println(format.format(new Date())); // 一年中的第几天 format = new SimpleDateFormat("yyyy.MM.dd D"); //2021.01.14 14 System.out.println(format.format(new Date())); // 一年中的第几周 format = new SimpleDateFormat("yyyy.MM.dd w"); //2021.01.14 3 System.out.println(format.format(new Date())); // 一月中的第几周 format = new SimpleDateFormat("yyyy.MM.dd W"); //2021.01.14 3 System.out.println(format.format(new Date())); // A.M./P.M.标记 format = new SimpleDateFormat("yyyy.MM.dd a"); //2021.01.14 下午 System.out.println(format.format(new Date())); // 一天中的第几个小时(1~24) format = new SimpleDateFormat("yyyy.MM.dd k"); //2021.01.14 14 System.out.println(format.format(new Date())); // 带有A.M./P.M.的小时 format = new SimpleDateFormat("yyyy.MM.dd K"); //2021.01.14 2 System.out.println(format.format(new Date())); // 时区 format = new SimpleDateFormat("yyyy.MM.dd z"); //2021.01.14 14 System.out.println(format.format(new Date()));

发表评论

快捷回复: 表情:
AddoilApplauseBadlaughBombCoffeeFabulousFacepalmFecesFrownHeyhaInsidiousKeepFightingNoProbPigHeadShockedSinistersmileSlapSocialSweatTolaughWatermelonWittyWowYeahYellowdog
评论列表 (暂无评论,216人围观)

还没有评论,来说两句吧...