js,java时间处理

1.JS获取时间格式为“yyyy-MM-dd HH:mm:ss”的字符串

function getTimeStr(){
    var myDate = new Date();

    var year = myDate.getFullYear(); //获取完整的年份(4位,1970-????)
    var month = myDate.getMonth(); //获取当前月份(0-11,0代表1月)
    month = month > 9 ? month : "0"+month;
    var day =  myDate.getDate(); //获取当前日(1-31)
    day = day > 9 ? day : "0"+day;
    var hours =  myDate.getHours(); //获取当前小时数(0-23)
    hours = hours > 9 ? hours : "0"+hours;
    var minutes =  myDate.getMinutes(); //获取当前分钟数(0-59)
    minutes = minutes > 9 ? minutes : "0"+minutes;
    var seconds =  myDate.getSeconds(); //获取当前秒数(0-59)
    seconds = seconds > 9 ? seconds : "0"+seconds;
   return year+"-"+month+"-"+day+" "+hours+":"+minutes+":"+seconds;
}

2.java字符串转时间“字符串可以是多种格式”

 public static void main(String[] args) {
        String strDate="2005年04月22日";
        //注意:SimpleDateFormat构造函数的样式与strDate的样式必须相符
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy年MM月dd日 ");
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //加上时间
        //必须捕获异常
        try {
            Date date=simpleDateFormat.parse(strDate);
            System.out.println(date);
        } catch(ParseException px) {
            px.printStackTrace();
        }
    }

3.java 计算两个时间之间的差多久

public static String getDatePoor(Date endDate, Date nowDate) {
 
    long nd = 1000 * 24 * 60 * 60;
    long nh = 1000 * 60 * 60;
    long nm = 1000 * 60;
    // long ns = 1000;
    // 获得两个时间的毫秒时间差异
    long diff = endDate.getTime() - nowDate.getTime();
    // 计算差多少天
    long day = diff / nd;
    // 计算差多少小时
    long hour = diff % nd / nh;
    // 计算差多少分钟
    long min = diff % nd % nh / nm;
    // 计算差多少秒//输出结果
    // long sec = diff % nd % nh % nm / ns;
    return day + "天" + hour + "小时" + min + "分钟";
}

猜你喜欢

转载自www.cnblogs.com/UncleWang001/p/9831458.html