类型转换5

在android 项目中用到的一些转换


1、普通的数据类型转换

1.1、String double转换

String -> double  


double -> String

String string;

string.valueOf(value)

1.2、 int  Integer 转换

Integer(int value) 
          构造一个新分配的 Integer 对象,它表示指定的 int 值。 
Integer(String s) 
          构造一个新分配的 Integer 对象,它表示 String 参数所指示的 int 值。 

int n=Integer.parseInt("");
将不是int类形的其他类型转为int类型
 
intInteger:
int a=3;
Integer A=new Integer(a);
:
Integer A=Integer.valueOf(a);

Integerint:
Integer A=new Integer(5);
int a=A.intValue();

至于Integer.parseInt(String str)则是将String类型转为int类型。

 

JAVA5.0 新特性支持自动封箱,可以直接使用 Integer itg = 5
正规应该是 Integer itg = new Integer(5); // 基本类型构造包装类
int i = itg.intValue(); //
包装类转为基本类型


1.3、数字显示格式

NumberFormat nf = NumberFormat.getInstance();

// say we need 2 digits

nf.setMinimumIntegerDigits(2); //两位

btn_state.setText(year + "-" + nf.format(mon) + "-" + nf.format(day));


DecimalFormat df = new DecimalFormat("0.###"); 没有小数不补0

 DecimalFormat df = new DecimalFormat("#.00");


1.4 小数点保留

new DecimalFormat("#.0").format(sumWeight / sumDay);// 转换为字符串 1位小数

new DecimalFormat("#").format(sumWeight / sumDay);// 转换为字符串 不要小数


WATER = (new BigDecimal(WATER)).setScale(1).doubleValue(); //double -> double。Scale不能用默认值。

BMI = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue(); //BigDecimal是精确计算,可以确定是四舍五入  还是不入之类的


1.5、短日期格式转换

Date currentTime = new Date();
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
  String dateString = formatter.format(currentTime);

1.Calendar 转化 String 
 //获取当前时间的具体情况,如年,月,日,week,date,分,秒等 
        Calendar calendat = Calendar.getInstance();

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(calendar.getTime());

 


2.String 转化Calendar

String str="2010-5-27";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");

Date date =sdf.parse(str);

Calendar calendar = Calendar.getInstance();

calendar.setTime(date);

 

 

3.Date 转化String

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

String dateStr=sdf.format(new Date());

 

 

 

4.String 转化Date 
String str="2010-5-27";

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

Date birthday = sdf.parse(str);

 

 

5.Date 转化Calendar

Calendar calendar = Calendar.getInstance();
calendar.setTime(new java.util.Date());

 

6.Calendar转化Date

Calendar calendar = Calendar.getInstance();
java.util.Date date =calendar.getTime();


参考:http://fjfj910.iteye.com/blog/1202219



ps:好像是第二次出这个类型转换的错误了,比较惭愧,记录下

int 时间戳转换为 Date时间

int time = 1447902000;


错误的写法:

Date date = new Date(time * 1000); 这样子是不会自动转换成long的。 偶还以为 new Date的参数是long的就会自动转换了,结果还是int 并不能自动转换


正确的写法:

Date date = new Date(time * 1000l);  加上显示转换符。 或者吧 time直接定义成long的 





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值