日期之间的转换

import android.text.TextUtils;

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

/**
* 日期的转换 工具类
*/

public class DateUtils {

/**
    * 字符串转换成时间格式 HH:mm
    * */
public static String convertToTime(String dateStr){

    String result = "00:00";

    if(TextUtils.isEmpty(dateStr)){
        return "00:00";
    }

    try{
        /***声明转换格式*/
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
        /***字符串转换成date*/
        Date date = simpleDateFormat.parse(dateStr);
        /**声明格式*/
        SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm");
        /**转化成需要的格式*/
        result = simpleDateFormat1.format(date);


    }catch(Exception e){
        /**转换异常*/
        result = "00:00";
    }

    return result;

}


/**
    * 字符串转换成特定的日期格式
    * */
public static String convertDate(String dateStr){
    String result = "加载中...";

    if(TextUtils.isEmpty(dateStr)){
        return "加载中...";
    }
    /**字符串转化成日期*/
    try{
        SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = sdf.parse(dateStr);
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy年MM月dd日");
        result = sdf1.format(date);
    }catch (Exception e){

    }

    return  result;
}


/**
    * 获取某一日期对应的周几
    * */
public static String  convertToWeek(String dateStr){
    String result = "加载中....";
    if(TextUtils.isEmpty(dateStr)){
        return result;
    }

    /**对应的转化后的日期*/
    String currentDate_str = "";
    String convertDate_str = "";
    Date convertDate_date = new Date();
    Date currentDate = new Date();
    try{
        /**转换字符串*/
        SimpleDateFormat sdf =   new SimpleDateFormat("yyyy-MM-dd");
        convertDate_date = sdf.parse(dateStr);
        /**转换字符类型*/
        currentDate_str = sdf.format(currentDate);
        convertDate_str = sdf.format(convertDate_date);

    }catch(Exception e){

    }

    String[] weeks = {"周日","周一","周二","周三","周四","周五","周六"};
    Calendar cal = Calendar.getInstance();
    cal.setTime(convertDate_date);
    int week_index = cal.get(Calendar.DAY_OF_WEEK) - 1;
    if(week_index<0){
        week_index = 0;
    }

    /**获取对应的week*/
    String weekStr = weeks[week_index];

    /**判断传入的日期是否和今天相一致.一致的话,则返回今天*/
    if(TextUtils.equals(currentDate_str,convertDate_str)){
        weekStr = "今天";
    }

    /**返回结果*/
    return weekStr;

}

}

你可能感兴趣的:(android)