Android 时间相关的转换

date转String

 public static String dateToString(Date date) {
         //日期格式化(括号内是自己想要的日期格式)
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月dd日");
        return format.format(date);
    }

String转date

public static Date stringToDate(String string) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date date = null;
        try {
            date = sdf.parse(string);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

date转时间戳

/**
     * 获取系统时间戳
     *
     * @return
     */
    public static long getCurrentTimeMillis() {
        long currTimeSeconds = System.currentTimeMillis();
        return currTimeSeconds;
    }

//没验证应该直接这样就行
date.getTime();

}

时间戳转date

//暂时
 SimpleDateFormat format =  newSimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
    Long time=newLong(445555555);  
    String d = format.format(time);  
    Date date=format.parse(d);  

date转calendar

  • 用calendar对年月日等单独操作很方便
Date date = new Date();  
Calendar cal = Calendar.getInstance();  
cal.setTime(date);  

//对calendar进行操作
 Calendar calendar=Calendar.getInstance();
 calendar.setTime(date);
 int year = calendar.get(calendar.YEAR);
 int month = calendar.get(calendar.MONTH) + addMonthTime;
 int day = calendar.get(calendar.DAY_OF_MONTH) + addDayTime;
 calendar.set(year, month, day);
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
 String dateStr = sdf.format(calendar.getTime());
 mTimeTv.setText(dateStr);

calendar转date

Calendar cal=Calendar.getInstance();  
Date() date=cal.getTime(); 

String转时间戳

    public static long stringToTimeMillis(String timeString) {
        String timeStamp = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        Date d;
        long l = 0;
        try {
            d = sdf.parse(timeString);
            l = d.getTime();
//                timeStamp = String.valueOf(l);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return l;
    }

时间戳转String

 public static String timeMillisToString(long millis, String pattern) {
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        String sd = sdf.format(new Date(millis));
        return sd;
    }

String转calendar

String str="2012-5-27";
SimpleDateFormat sdf= new SimpleDateFormat("yyyy-MM-dd");
Date date =sdf.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);

calendar转String

Calendar calendat = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(calendar.getTime());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值