Java 字段类型互相转换

1.String和date 互转
1.1 日期转字符串(格式化)

package com.test.dateFormat;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.junit.Test;

public class Date2String {
@Test
public void test() {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.format(date));
sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
System.out.println(sdf.format(date));
}
}

运行结果

2016-10-24
2016-10-24 21:59:06
2016年10月24日 21:59:06
2、字符串转日期(解析)

package com.test.dateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.junit.Test;

public class String2Date {
@Test
public void test() throws ParseException {
String string = "2016-10-24 21:59:06";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.parse(string));
}
}
运行结果

1
Mon Oct 24 21:59:06 CST 2016
在字符串转日期操作时,需要注意给定的模式必须和给定的字符串格式匹配,否则会抛出java.text.ParseException异常,例如下面这个就是错误的,字符串中并没有给出时分秒,那么SimpleDateFormat当然无法给你凭空解析出时分秒的值来

package com.test.dateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.junit.Test;

public class String2Date {
@Test
public void test() throws ParseException {
String string = "2016-10-24";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.println(sdf.parse(string));
}
}
运行报错

Exception in thread "main" java.text.ParseException: Unparseable date: "2016-10-24"
at java.text.DateFormat.parse(DateFormat.java:366)
at com.test.dateFormat.String2Date.main(String2Date.java:19)
不过,给定的模式比字符串少则可以

package com.test.dateFormat;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import org.junit.Test;

public class String2Date {
@Test
public void test() throws ParseException {
String string = "2016-10-24 21:59:06";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(sdf.parse(string));
}
}
运行结果

Mon Oct 24 00:00:00 CST 2016

一.将long型转化为int型,这里的long型是基础类型:

long a = 10; int b = (int)a;

二.将Long型转换为int 型的,这里的Long型是包装类型:

Long a = 10; int b=a.intValue();

三.将int型转化为long型,这里的int型是基础类型:

int a = 10;long b = (int)a;

四.将Integer型转化为long型,这里的Integer型是包装类型:

int a = 10;Long b = a.longValue();
————————————————
版权声明:本文为CSDN博主「ZK_小姜」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u014039577/article/details/37925611

posted @ 2021-12-21 10:26  何家有子初长成  阅读(343)  评论(0编辑  收藏  举报