JS与JAVA及Oracle的日期对比与常用案例

做开发的时候,有时候JS与Java和Oracle的日期格式不匹配。这时候需要使JS的日期与Oracle的Date一样才能保证数据的一致。

JS日期格式:

	Date.prototype.format = function(fmt) { 
	    var o = { 
	       "M+" : this.getMonth()+1,                 // 月份
	       "d+" : this.getDate(),                    // 日
	       "h+" : this.getHours(),                   // 小时
	       "m+" : this.getMinutes(),                 // 分
	       "s+" : this.getSeconds(),                 // 秒
	       "q+" : Math.floor((this.getMonth()+3)/3), // 季度
	       "S"  : this.getMilliseconds()             // 毫秒
	   }; 
	   if(/(y+)/.test(fmt)) {
	           fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length)); 
	   }
	    for(var k in o) {
	       if(new RegExp("("+ k +")").test(fmt)){
	            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
	        }
	    }
	   return fmt; 
	}  

	var time = new Date().format("yyyy-MM-dd hh:mm:ss");

	$("#trbrqs").val(time);

	$('#trbrqs').attr("readonly","readonly");

Js获取当前日期

<script type="text/javascript">
	var date=new Date();
	document.write(date.getTime()+"<br/>");
	document.write(date.getFullYear()+"<br/>");
	document.write((date.getMonth()+1)+"<br/>");
	document.write(date.getDate()+"<br/>");
	var today=date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日";
	document.write(today+"<br/>");
	document.write(date.getHours()+"<br/>");
	document.write(date.getMinutes()+"<br/>");
	document.write(date.getSeconds()+"<br/>");
	today=date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日  "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
	document.write(today+"<br/>");
	var day=date.getDay();
	var week;
	switch(day){
	case 0:week="星期日";break;
	case 1:week="星期一";break;
	case 2:week="星期二";break;
	case 3:week="星期三";break;
	case 4:week="星期四";break;
	case 5:week="星期五";break;
	case 6:week="星期六";break;
	}
	document.write(week+"<br/>");
	today=date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日  "+week+" "+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds();
	document.write(today+"<br/>");
</script>

js获取当月的第一天与最后一天

$(function() {
     var nowdays = new Date();  
     var year = nowdays.getFullYear();
     var month = nowdays.getMonth()+1;
     if(month==0)
     {
         month=12;
         year=year-1;
     }
     if (month < 10) {
         month = "0" + month;
     }
     
     var firstDay = year + "-" + month + "-" + "01";
     var myDate = new Date(year, month, 0);
     var lastDay = year + "-" + month + "-" + myDate.getDate();
 
     var start = $("#ks").val(firstDay)
     var end = $("#js").val(lastDay);

  ));  

Java日期格式化

Java日期工具类Calendar

获取当前日期

		Calendar calendar=Calendar.getInstance();
		System.out.println(calendar.get(Calendar.YEAR));
		System.out.println(calendar.get(Calendar.MONTH)+1);
		
		System.out.println("现在是:"+calendar.get(Calendar.YEAR)+"年"
				+(calendar.get(Calendar.MONTH)+1)+"年"
				+calendar.get(Calendar.DAY_OF_MONTH)+"日"
				+calendar.get(Calendar.HOUR_OF_DAY)+"时"
				+calendar.get(Calendar.MINUTE)+"分"
				+calendar.get(Calendar.SECOND)+"秒");
	}

String类型转为Date类型

 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
					String TimeNow = df.format(new Date());
					Date time = null;
		 			try {
						time = df.parse(TimeNow);
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

Java中用SimpleDateFormate日期字符串与日期格式的转换,例如

	/**
	 * 将日期字符串转换成一个日期对象
	 * @param dateStr 日期字符串
	 * @param format 格式
	 * @return
	 * @throws ParseException
	 */
	public static Date formatDateStr(String dateStr,String format) throws ParseException{
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		return sdf.parse(dateStr);
	}
	
	
	/**
	 * 将日期对象格式化为指定格式的日期字符串
	 * @param date 传入的日期对象
	 * @param format 格式
	 * @return
	 */
	public static String formatDate(Date date,String format){
		String result="";
		SimpleDateFormat sdf=new SimpleDateFormat(format);
		if(date!=null){
			result=sdf.format(date);
		}
		return result;
	}
	
	public static void main(String[] args) throws ParseException {
		Date date=new Date();
		/*SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		System.out.println(sdf.format(date));*/
		
		System.out.println(formatDate(date,"yyyy-MM-dd"));
		System.out.println(formatDate(date,"yyyy-MM-dd HH:mm:ss"));
		System.out.println(formatDate(date,"yyyy年MM月dd日 HH时mm分ss秒"));
		
		String dateStr="1989-11-02 10:04:07";
		Date date2=formatDateStr(dateStr,"yyyy-MM-dd HH:mm:ss");
		System.out.println(formatDate(date2,"yyyy-MM-dd HH:mm:ss"));
	}

Date类型比较日期大小相差几天,超过一定时间不显示

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
		String nowTime =df.format(new Date());
		for(CheckAdvice openItem:bottomLeftList) {
			if(null!=openItem) {
				String Time = openItem.getDuration();
				if(null!=Time) {
					long duraLong = Long.parseLong(Time);
					String createTime = openItem.getCreateTime();
					try {
						Date nowDate = df.parse(nowTime);
						Date beginDate = df.parse(createTime);
						long betweenTime =(nowDate.getTime()-beginDate.getTime())/(24*60*60*1000);  
						if(betweenTime>duraLong) { //大于公示期不显示
							continue;
						}else {
							bottomLeftTimeList.add(openItem);
						}
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		}

SimpleDateFormate获取指定的日期

@Service
public class IndexService {
	public List<IBean> getGztzd(String type) {
		String date = getDate(type);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String time = format.format(Calendar.getInstance().getTime());


	private String getDate(String type) {// 处理日期
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		String date = "";
		if (type.equals("1")) {// 上个星期的日期
/*			c.setTime(new Date());
			c.add(Calendar.DATE, -7);*/
			c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); 
			c.set(Calendar.HOUR_OF_DAY, 0);
			c.set(Calendar.MINUTE, 0);
			c.set(Calendar.SECOND, 0);
			Date day = c.getTime();
			date = format.format(day);
		}
		if (type.equals("2")) {// 上个月的日期 只考虑当年 不包含从 今年的1月份到去年的12月
			c.setTime(new Date());
			 c.add(Calendar.MONTH, 0);  
		     c.set(Calendar.DAY_OF_MONTH, 1); 
			 date = format.format(c.getTime());
			
		}
		if (type.equals("3")) {// 上一年的日期 只考虑当年 
            c.add(Calendar.YEAR, 0);  
            c.set(Calendar.DAY_OF_YEAR, 1);
            date = format.format(c.getTime());
		}
		return date;	
	}




	private String ztrq(String time){//昨天的日期
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		String date = "";
		c.setTime(new Date());
		c.add(Calendar.DATE,-1);
		date = format.format(c.getTime());
		return date;
	}
	
	private String ylrq(String time){//上个月的日期 考虑跨年 今年的1月份计算去年12月份 一个月前的日期
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		String date = "";
		c.setTime(new Date());
		 c.add(Calendar.MONTH, 0);  
	     c.set(Calendar.DAY_OF_MONTH, 1); 
		 date = format.format(c.getTime());
		return date;
	}
	
	private String nlrq(String time){//去年的日期 同上
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Calendar c = Calendar.getInstance();
		String date = "";
		c.setTime(new Date());
        c.add(Calendar.YEAR, 0);  
        c.set(Calendar.DAY_OF_YEAR, 1);
        date = format.format(c.getTime());
		return date;
	}
	

Java把其他日期格式统一为oracle中的默认日期格式

  else if ("TIME".equalsIgnoreCase(columnValue[0])) {
			 String StrVal = value.toString();
				 try {
				Date d1 = new SimpleDateFormat("yyyy年MM月dd日").parse(StrVal);
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
				String time = format.format(d1);
				value = time;
					} catch (ParseException e) {
						// TODO Auto-generated catch block
							e.printStackTrace();
						} 
						 } 

Java获取上个月的最后一天

	String lastDay = lastMonthDay();
	private String lastMonthDay(){
/*		  Calendar cal = Calendar.getInstance();
		  //下面可以设置月份,注:月份设置要减1,所以设置1月就是1-1,设置2月就是2-1,如此类推
		  cal.set(Calendar.MONTH, 1-1);
		  //调到上个月
		  cal.add(Calendar.MONTH, -1);
		  //得到一个月最最后一天日期(31/30/29/28)
		  int MaxDay=cal.getActualMaximum(Calendar.DAY_OF_MONTH);
		  //按你的要求设置时间
		  cal.set( cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), MaxDay, 23, 59, 59);
		  //按格式输出
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		  String date = "";
		  date = sdf.format(cal.getTime());*/
		  Calendar c = Calendar.getInstance();
		  c.add(Calendar.MONTH, -1);
		  SimpleDateFormat format =  new SimpleDateFormat("yyyy-MM");
		  String time = format.format(c.getTime());
		//得到一个月最后一天日期(31/30/29/28)
		  int MaxDay=c.getActualMaximum(Calendar.DAY_OF_MONTH);
		  //按你的要求设置时间
		  c.set( c.get(Calendar.YEAR), c.get(Calendar.MONTH), MaxDay, 23, 59, 59);
		  //按格式输出
		  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		  String date = sdf.format(c.getTime()); //上月最后一天
		return date;
	}
}

java时间比较

	 DateFormat df = new SimpleDateFormat("yyyy-MM-dd hh:mm");
		 try {
			Date dt1 = df.parse(startTime);
			Date dt2 = df.parse(endTime);
			if(dt1.getTime() > dt2.getTime())
			{
				return FAILURE
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

java before after 比较时间的大小

	public boolean sendMetting(Date startTime,String orgType,String activityType) {
						Date date = format.parse(activityTime.substring(0, 10));
						if(!startTime.before(date)) { //before 如果startTime小于date为true
							if(userIds != null && userIds.length() > 0) {

							}
						}
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				  
    }  
	
	//获取当前季度的开始时间
	public static Date getCurrentQuarterStartTime() { 
		Calendar c = Calendar.getInstance(); 
		int currentMonth = c.get(Calendar.MONTH) + 1; 
		SimpleDateFormat longSdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat shortSdf = new SimpleDateFormat("yyyy-MM-dd");
		Date now = null; 
		try { 
		if (currentMonth >= 1 && currentMonth <= 3) 
		c.set(Calendar.MONTH, 0); 
		else if (currentMonth >= 4 && currentMonth <= 6) 
		c.set(Calendar.MONTH, 3); 
		else if (currentMonth >= 7 && currentMonth <= 9) 
		c.set(Calendar.MONTH, 6); 
		else if (currentMonth >= 10 && currentMonth <= 12) 
		c.set(Calendar.MONTH, 9); 
		c.set(Calendar.DATE, 1); 
		String nowe = null;
		nowe = shortSdf.format(c.getTime()); 
		now = shortSdf.parse(nowe);   
		} catch (Exception e) { 
		e.printStackTrace(); 
		} 
		return now; 
		}
	
	//当月的开始时间
	public static Date getLastMonthStartTime() {  
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.MONTH, 0);
		cal.set(Calendar.DAY_OF_MONTH,1);//设置为1号,当前日期既为本月第一天 
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		Date date = cal.getTime();
        
        return date;
    }
	
	
	//获取当年的开始时间
	public static Date getCurrentYearStartTime() { 
	 	SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance(); 
        Date now = null; 
        try { 
            c.set(Calendar.MONTH, 0); 
            c.set(Calendar.DATE, 1); 
            c.set(Calendar.HOUR_OF_DAY, 0);
    		c.set(Calendar.MINUTE, 0);
    		c.set(Calendar.SECOND, 0);
            now = format.parse(format.format(c.getTime())); 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
        return now; 
	} 
	 
}

Java Calendar

有时候我们需要对格式化的日期进行操作,比如在Java中计算一年前的今天等日期的计算,就需要用到Calendar抽象类。一般情况都需要与SimpleDateFormate配合使用

 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
 SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd");
 java.util.Date timeNow;
 java.util.Date timeNow1;
 String qn = null;
 	
 try {
 timeNow = df1.parse(month);
 String date1 = df.format(timeNow);
 timeNow1 = df.parse(date1);
 Calendar calendar = Calendar.getInstance();  
 calendar.setTime(timeNow1); 
 calendar.add(Calendar.YEAR, -1); //计算一年前的日期
 qn = df.format(calendar.getTime()); //输出格式为 yyyy-MM-dd的日期} catch (ParseException e) {// TODO Auto-generated catch block e.printStackTrace(); }

Oracle的日期格式化需要用到to_date函数

oracle计算一年前的今天的日期

create or replace view v_rgq_one as
select "CODE","NAME","CUR_TIME","CUR_AMOUNT","VARIATION","LAST_TIME","LAST_AMOUNT" from (
select 
       cur_year.sj  as cur_time,
       cur_year.yql as cur_amount,
       cur_year.yql-last_year.yql as variation,
       last_year.sj    as last_time,
       last_year.yql  as last_amount
  from SMCOUNT cur_year left join sm_count last_year
  on cur_year.sj =
       to_char(add_months(to_date(last_year.sj, 'YYYY-MM-DD'), +12),
               'YYYY-MM-DD')
 order by cur_year.sj desc);

猜你喜欢

转载自blog.csdn.net/qq_35029061/article/details/80781333