Android开发 很常用时间处理工具

1.获取当前系统的毫秒值
/**
 * 返回当前时间的毫秒值
 *
 * @return
 */
public static long getDateMilliscond() {
    return System.currentTimeMillis();
}
2.给定一个时间字符串和其格式,获取其毫秒值
 /**
 * String类型转换为long类型
 */
// strTime要转换的String类型的时间
// formatType时间格式
// strTime的时间格式和formatType的时间格式必须相同
public static long stringTimeToLong(String strTime, String formatType)
        throws ParseException {
    Date date = stringToDate(strTime, formatType); // String类型转成date类型
    if (date == null) {
        return 0;
    } else {
        long currentTime = dateToLong(date); // date类型转成long类型
        return currentTime;
    }
}
3.给定一个时间字符串和其格式,转化为另一SimpleDateFormat格式返回
    /**
 * String类型转换为String类型
 * @param strTime 要转换的String类型的时间
 * @param formatTypeForm 时间格式,strTime的时间格式和formatType的时间格式必须相同
 * @param formatTypeTo 目标时间格式
 * @return
 * @throws ParseException
 */
public static String stringTimeToString(String strTime, String formatTypeForm, String formatTypeTo)
        throws ParseException {
    Date date = stringToDate(strTime, formatTypeForm); // String类型转成date类型
    SimpleDateFormat sdf = new SimpleDateFormat(formatTypeTo);
    if (date == null) {
        return "";
    } else {
        return sdf.format(date);
    }
}
4.给定一个时间字符串和其格式,转化为另一格式返回,去掉无意义的0,比如说 **** 年 * 月 * 号
/**
 * yyyy-MM-dd HH:mm:ss类型转换为****年*月*号
 */
// strTime要转换的String类型的时间
// formatType时间格式
// strTime的时间格式和formatType的时间格式必须相同
public static String stringTimeToCalendarString(String strTime, String formatTypeForm)
        throws ParseException {
    Date date = stringToDate(strTime, formatTypeForm); // String类型转成date类型

    Calendar cal = Calendar.getInstance();
    cal.setTime(date);
    return cal.get(Calendar.YEAR) + "年" + (cal.get(Calendar.MONTH) + 1) + "月" + cal.get(Calendar.DAY_OF_MONTH) + "号";
}
5.给定毫秒值,获取格式化后的字符串(可结合方法1直接获取格式化后的当前系统时间)
 /**
 * long类型转换为String类型
 */
// currentTime要转换的long类型的时间
// formatType要转换的string类型的时间格式
public static String longToString(long currentTime, String formatType)
        throws ParseException {
    Date date = longToDate(currentTime, formatType); // long类型转成Date类型
    String strTime = dateToString(date, formatType); // date类型转成String
    return strTime;
}
6.获取当前年份
/**
 * 获取年
 */
public static int getYearNow() {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.YEAR);
}
7.获取当前月份
/**
 * 获取月
 */
public static int getMonthNow() {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.MONTH) + 1;
}
8.获取当前日期(当月的第?天)
 /**
 * 获取日
 */
public static int getDayNow() {
    Calendar calendar = Calendar.getInstance();
    return calendar.get(Calendar.DAY_OF_MONTH);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值