浅谈:字符串、时间格式的转换

字符串与时间格式的转换

-----常用的方法:1、拼接字符串的格式【String类型的一些常用的方法】;

        2、simpledateformat格式

        3、Date格式

1、SimpleDateFormat的用法:【定义输出结果的样式,】

  SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

  1.1常用的方法:

    sf.format(Date);将给定Date格式化为日期/时间字符串,并将结果添加到给定的StringBuffer

    sf.parse(String);解析字符串文本,生成Date类型

2、Date的用法:【来自util包】

    Date now = new Date();输出当前系统的时间;

    now.getTime();返回自1970年1月1日00:00:00以来此date对象表示的毫秒数

    now.setTime();设置此Date对象,以表示1970年1月1日00:00:00以后time毫秒数的时间

     还有now.after(date);now.before(datee);now.compareTo(date);now.equals(object);都是没有过时的一些方法,其他的都是过时的方法,过时的方法有时候用起来没有影响,有时候是有影响的;

    【过时的方法:获取时间的年月日,或者设置时间的年月日等等一系列的方法】

3、String的用法:【常用的方法】

    String str = "sdasdhaksjdhaskdhk";

    char--charAt(index);返回指定索引的char值。

    String--concat(String);将指定字符串连接到此字符串的结尾。

    int--indexOf(char);返回指定字符串在此字符中第一次出现处的索引。

    String--indexOf(String);返回指定子字符串在此字符串中第一次出现处的索引。

    int--length();返回此字符串的长度。

    isEmpty();当且仅当length()为0时返回true。

    String[]--split(string);根据给定的字符、字符串匹配,进行拆分此字符串。

    String--toString()。返回此对象本身(它已经是一个字符串)。

    String--trim()。返回字符串的副本,忽略前导空白和尾部空白。

4、输出当前系统的时间:

Date d = new Date();      或者:

System.out.println(d);                  System.out.println(new Date());

5、String类型格式:

  

6、随便输入一个“字符串”的时间格式,将其转换成一个Date类型的时间格式:

练习一:

  //拆分字符串的格式进行输出一个指定格式的字符串
  String a = "1990-2-1";
  String[] b = a.split("-");
  String da=b[0]+"年"+b[1]+"月"+b[2]+"日";
  System.out.println(da);

    --------------输出结果是:1990年2月1日

练习二:sql类型的时间格式转换成util类型的时间格式

package com.date;

import java.util.Date;
//sql类型的时间格式转换成util类型的时间格式;
public class Test {
	 public static void main(String[] args)
	 {
		 Test t = new Test();
		 Date d = t.creatRegDate();
		 System.out.println(d);
	 }
	 public java.sql.Date creatRegDate() {
			Date udate = new Date();//当前系统的时间
			//先获取到时间的毫秒数,
			//然后再通过毫秒数转换成sql类型的时间格式,就可以转换成需要的那种时间格式;
			java.sql.Date sdate = new java.sql.Date(udate.getTime());
//			System.out.println("获得的毫秒数:"+udate.getTime());
			return sdate;
		}
}

  

  

本人目前处于学习阶段,各位大神多多提宝贵的建议!
原文地址:https://www.cnblogs.com/FanSunny/p/4826873.html