格式化时间日期(Java)

工作中遇到的一个问题,顺便记录一下。

假设获取到的时间日期的值为一个String类型,例如:String time_now = "2018-4-28  17:04:05";

当我们需要单独取前面的日期或者后面的时间的时候,我们需要经过处理:

private String getTime(String end) {
		String time = null;
		if(end == null) {
			return "";
		}else {
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date d1 = df.parse(end);
			time = df.format(d1);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return time; 
		}
	}
由Date获取当前的时间的标准输出为:

Date ss= new Date();

Sat Apr 28 17:17:22 CST 2018    这样的数据

经过这样的格式化处理之后会得到标准的String类型的时间:

        SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
        String time = format0.format(ss.getTime()); 
        System.out.println("格式化0:" + time);  
        SimpleDateFormat format1 = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分ss秒");  
        time = format1.format(ss.getTime());  
        System.out.println("格式化1:" + time);  
输出结果为:格式化结果0:2018-04-28 17:19:55
            格式化结果1:2018年04月28日 17时19分55秒


猜你喜欢

转载自blog.csdn.net/sinat_34153600/article/details/80137186