【Java语言基础】Java中Date、String、Long三种类型互相转换

总结:parse要throws ParseException,System.currentTimeMillis()不要写成System.currentTimeMills()

Date date = new Date();//获取当前时间

DateFormat df = new SimpleDateFormat(“yyyy-MM-dd HH:mm:ss”);

1.将date型的数据转换成特定的String型字符串

   String sDate=df.format(date);

2.把String型的字符串转换成特定格式的date类型

  String sDate="2001.12.12-08.23.21";

  df = new SimpleDateFormat("yyyy.MM.dd-HH.mm.ss");

  try {

 		Date d = df.parse(dStr);


} catch (ParseException pe) {

		 System.out.println(pe.getMessage());
}

3.Date转long型

Date date = new Date();
long dateTime = date.getTime();

4.long型转Date

long dateTime = 14830682769461;
Date date = new Date(dateTime);
System.out.println(date.toString());

下面将这三个步骤串联起来演示一遍怎么搞的:

import java.util.*;
import java.text.*;
class Demo5
{
	public static void main(String[] args) throws ParseException
	{
		String str = "14###三月##21";
		//1.创建格式化对象	格式要一致
		SimpleDateFormat sdf2 = new SimpleDateFormat("yy###MMM##d");
		//2.将String型转为Date型
		Date date = sdf2.parse(str);
		System.out.println(date);
		
		//3.将Date型转为String型
		String str1 = sdf2.format(date);
		System.out.println(str1);
		
		//4.在2.的基础上将Date型的日期转换为 yyyy年MM月dd日 格式
		SimpleDateFormat sdf3 = new SimpleDateFormat("yyyy年MM月dd日");
		//然后再转为String型输出
		String strDate = sdf3.format(date);
		System.out.println(strDate);
	}
	
}

下面的给出例子,求你出生到现在已经多少天了?

String类型SimpleDateFormat格式化、String型转Date型、String型再SimpleDateFormat

import java.text.*;
import java.util.*;
class Demo6
{
	public static void main(String[] args)
		throws ParseException
	{
		//传入String型的生日
		String birth = "1997-05-23";
		time(birth);
	}
	
	public static void time(String birth) 
		throws ParseException
	{
		//1.创建SimpleDateFormat 日期格式化对象
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		//2.输入的日期格式转换为Date类型,同时抛出异常并交给系统处理
		Date date = sdf.parse(birth);
		//3.将Date型转换为long类型
		long dateTime1 = date.getTime();
		//4.获取系统当前时间
		long dateTime2 = System.currentTimeMillis();
		long day = (dateTime2-dateTime1)/1000/60/60/24;
		//5.测试算的天数对不对,看你是不是有year岁了
		long year = day/360;
		
		System.out.println(day);
		
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值