El desarrollo y el formato de codificación de la fecha (a)

El desarrollo y la codificación del formato de fecha

formato de fecha js

js formato de fecha para obtener la hora actual

JS no coincide con el formato de fecha de Java y Oracle, el mes antes de que el formato generado por JS fecha con 0.

Una forma,

Date.prototype.format = function (format) { 
    var o = {  
        "M+": this.getMonth() + 1, // month  
        "d+": this.getDate(), // day  
        "h+": this.getHours(), // hour  
        "m+": this.getMinutes(), // minute  
        "s+": this.getSeconds(), // second  
        "q+": Math.floor((this.getMonth() + 3) / 3), // quarter  
        "S": this.getMilliseconds()  
        // millisecond  
    }; 
    if (/(y+)/.test(format))  
        format = format.replace(RegExp.$1, (this.getFullYear() + "")  
            .substr(4 - RegExp.$1.length));  
    for (var k in o)  
        if (new RegExp("(" + k + ")").test(format))  
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));  
    return format;  
}
var dt= new Date(data); 

return dt.format("yyyy-MM-dd hh:mm:ss");

Segunda forma: hh DD-AAAA-MM: mm: ss

	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");

Tres maneras: AAAAMMDD

		function getNowFormatDate() 
        { 
           var day = new Date(); 
           var Year = 0; 
           var Month = 0; 
           var Day = 0; 
           var CurrentDate = ""; 
           Year       = day.getFullYear();//ie火狐下都可以 
           Month      = day.getMonth()+1; 
           Day        = day.getDate(); 
           CurrentDate += Year + ""; 
           if (Month >= 10 ) 
           { 
            CurrentDate += Month + ""; 
           } 
           else
           { 
            CurrentDate += "0" + Month + ""; 
           } 
           if (Day >= 10 ) 
           { 
            CurrentDate += Day ; 
           } 
           else
           { 
            CurrentDate += "0" + Day ; 
           } 

           return CurrentDate; 
        } 

      var namesalt = getNowFormatDate();

 

js objeto Date

En fecha JavaScript es su base de objetos, por lo que queremos conseguir y las operaciones en la fecha, hay que crear instancias de objetos.

1. Crear un objeto fecha
  objFecha var = new Date ();
  contendrá información sobre la hora local, incluyendo el año, mes, semana, día, hora 

  Nota: el mes y la semana se cuentan desde 0

2. Fecha de métodos de adquisición

Date() 返回当日的日期和时间。 
getDate() 从 Date 对象返回一个月中的某一天 (1 ~ 31)。 
getDay() 从 Date 对象返回一周中的某一天 (0 ~ 6)。
getMonth() 从 Date 对象返回月份 (0 ~ 11)。 
getFullYear() 从 Date 对象以四位数字返回年份。
getYear() 请使用 getFullYear() 方法代替。
getHours() 返回 Date 对象的小时 (0 ~ 23)。
getMinutes() 返回 Date 对象的分钟 (0 ~ 59)。
getSeconds() 返回 Date 对象的秒数 (0 ~ 59)。
getMilliseconds() 返回 Date 对象的毫秒(0 ~ 999)。
getTime() 返回 1970 年 1 月 1 日至今的毫秒数。
getTimezoneOffset() 返回本地时间与格林威治标准时间 (GMT) 的分钟差。 

3. El método de ajuste de la fecha

setDate() 设置 Date 对象中月的某一天 (1 ~ 31)。
setMonth() 设置 Date 对象中月份 (0 ~ 11)。
setFullYear() 设置 Date 对象中的年份(四位数字)。 
setYear() 请使用 setFullYear() 方法代替。 
setHours() 设置 Date 对象中的小时 (0 ~ 23)。 
setMinutes() 设置 Date 对象中的分钟 (0 ~ 59)。
setSeconds() 设置 Date 对象中的秒钟 (0 ~ 59)。 
setMilliseconds() 设置 Date 对象中的毫秒 (0 ~ 999)。 
setTime() 以毫秒设置 Date 对象。
setUTCDate() 根据世界时设置 Date 对象中月份的一天 (1 ~ 31)。 
setUTCMonth() 根据世界时设置 Date 对象中的月份 (0 ~ 11)。 
setUTCFullYear() 根据世界时设置 Date 对象中的年份(四位数字)。 
setUTCHours() 根据世界时设置 Date 对象中的小时 (0 ~ 23)。
setUTCMinutes() 根据世界时设置 Date 对象中的分钟 (0 ~ 59)。
setUTCSeconds() 根据世界时设置 Date 对象中的秒钟 (0 ~ 59)。 
setUTCMilliseconds() 根据世界时设置 Date 对象中的毫秒 (0 ~ 999)。 
<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 el primer día del mes y el último día de cálculo

$(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);

  ));  

 

visualización del tiempo de cuenta atrás

function getcha (now,end) {
   var arr=[];
	var cha=(end.getTime()-now.getTime())/1000;
	var days=parseInt(cha/(60*60*24));
	arr.push(days)
		cha%=(60*60*24);
	var hours=parseInt(cha/(60*60));
	arr.push(hours)
		cha%=60*60;
	var mints=parseInt(cha/60);
	arr.push(mints)
	var sends=cha%60;
	arr.push(sends)

	return arr;
	}

window.onload=function  () {
 var spans=document.getElementsByTagName("span");
    var end=new Date();
    end.setFullYear(2012);
	end.setMonth(7);
	end.setDate(12);
	end.setHours(12);
	end.setMinutes(0);
	end.setSeconds(0);
   var now=new Date();
     for (var i=0; i<getcha (now,end).length; i++) {
	   spans[i].innerHTML=getcha (now,end)[i]
     } 

  

   setInterval(function  () {
     var now=new Date();
     for (var i=0; i<getcha (now,end).length; i++) {
	   spans[i].innerHTML=getcha (now,end)[i]
     } 
   },1000)
}

<div>
距离奥运会还有<span></span>天<span></span>小时<span></span>分钟<span></span>秒
</div>

 

formato de fecha de Oracle

formato de fecha de Oracle para obtener la hora actual

La definición de formato de fecha de Oracle

       Year:      
        yy two digits 两位年                显示值:07 
        yyy three digits 三位年                显示值:007 
        yyyy four digits 四位年                显示值:2007 
            
        Month:      
        mm    number     两位月              显示值:11 
        mon    abbreviated 字符集表示          显示值:11月,若是英文版,显示nov     
        month spelled out 字符集表示          显示值:11月,若是英文版,显示november 
          
        Day:      
        dd    number         当月第几天        显示值:02 
        ddd    number         当年第几天        显示值:02 
        dy    abbreviated 当周第几天简写    显示值:星期五,若是英文版,显示fri 
        day    spelled out   当周第几天全写    显示值:星期五,若是英文版,显示friday        
        ddspth spelled out, ordinal twelfth 
             
              Hour: 
              hh    two digits 12小时进制            显示值:01 
              hh24 two digits 24小时进制            显示值:13 
              
              Minute: 
              mi    two digits 60进制                显示值:45 
              
              Second: 
              ss    two digits 60进制                显示值:25 
              
              其它 
              Q     digit         季度                  显示值:4 
              WW    digit         当年第几周            显示值:44 
              W    digit          当月第几周            显示值:1 
              
        24小时格式下时间范围为: 0:00:00 - 23:59:59....      
        12小时格式下时间范围为: 1:00:00 - 12:59:59 .... 

Por lo general, en forma de un tiempo de formatos de fecha sello se almacenan en la base de datos, la interfaz de front-end para consulta a través de las páginas, algunos de los atributos de un objeto volveremos a revisar la página.

 

@DateTimeFormat (patrón = "aaaa-MM-dd HH: mm: ss")

La razón: los datos transmitidos en la última página, en la forma de una cadena. Por lo que el formato de hora de estar equivocado. Añadir esta nota, la cadena de formato de tiempo de fondo se puede resolver. Pero detrás del escenario llegó a la recepción no puede resolver. Que tiene que hacer lo siguiente.

 

comentario @JsonFormat

                    <tr style="height: 50px">
                        <th style="width: 70px">拆除日期:</th>
                        <td style="width: 230px" colspan="3">
                            <input name="removeTime" class="easyui-my97" data-options="required:true" style="width: 200px;" >
                        </td>
                    </tr>
                        <td style="width: 200px" colspan="3">
                            <input name="approveTime" class="easyui-textbox" style="width: 170px;" >
                        </td>
@JsonFormat(pattern = "yyyy-MM-dd")
@DateTimeFormat(pattern = "yyyy-MM-dd")
private Date removeTime;//拆除日期
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date approveTime;//审批时间

 

Oracle para encontrar el primer día del mes, último día 

  SELECT Trunc(Trunc(SYSDATE, 'MONTH') - 1, 'MONTH') First_Day_Last_Month, 
       Trunc(SYSDATE, 'MONTH') - 1 / 86400 Last_Day_Last_Month, 
       Trunc(SYSDATE, 'MONTH') First_Day_Cur_Month, 
       LAST_DAY(Trunc(SYSDATE, 'MONTH')) + 1 - 1 / 86400 Last_Day_Cur_Month 
   FROM dual; 

 

fecha de cálculo de Oracle hace un año

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);

 

Ver a tablas de datos hace una hora

select * from ct_user as of timestamp sysdate-(1/(24));

ADD_MONTHS (x, y) o ADD_MONTHS (tiempos, meses) Función: muchos meses después de la fecha de calcular, si éste es negativo, muchos meses antes de la fecha de la fecha actual se calcula.

select add_months(sysdate,-6) from dual;//查询的结果是当前时间半年前的时间
select add_months(sysdate,6) from dual;//查询的结果是当前时间半年后的时间
 select ename, hiredate from emp where hiredate <= add_months(sysdate, -288);//入职时间超过24年-288 = -24*12

 

last_day (): Devuelve la fecha del último día del mes;

select last_day(sysdate) from dual;//查询当前月份的最后一天:
select last_day(to_date('1992-10-09','yyyy-mm-dd')) from dual;//查询某天所在月份的最后一天:

 

TO_DATE (función), la cadena hasta la fecha

Nota: entre mayúsculas y minúsculas, y el MM mm SQL se considera que es el mismo código de formato, utilizando SQL de Oracle mi minutos en lugar de

Otras 24 horas que se muestran en la forma de uso HH24

update t_date set d3=to_date('2016-12-20','YYYY-MM-DD') where id=1;

update t_date set d3=to_date('2016-12-20 18:31:34','YYYY-MM-DD HH24:MI:SS') where id=1;

El número de días entre dos fechas      

    select floor(sysdate - to_date('20020405','yyyymmdd')) from dual;   

Suplemento; busque el número de días 2002-02-28 a 2002-02-01 habitación excepto lunes y siete  

  select count(*)      
   from ( select rownum-1 rnum      
       from all_objects      
       where rownum <= to_date('2002-02-28','yyyy-mm-dd') - to_date('2002-      
       02-01','yyyy-mm-dd')+1      
      )      
   where to_char( to_date('2002-02-01','yyyy-mm-dd')+rnum-1, 'D' )      
        not in ( '1', '7' )      

 

MONTHS_BETWEEN () devuelve la función del número de meses entre dos fechas. Si el mismo número de días dentro de los dos días del mes, o es el último día de un mes en particular para devolver un número entero, de lo contrario, devuelve el valor decimal, el número de días que quedan 1 / mes por día de 31 meses. Si la fecha 1 de la fecha 2 pequeña, se devuelve un valor negativo.

months_between(to_date('1999.11.29','yyyy.mm.dd'), to_date('1998.11.29','yyyy.mm.dd')) 

返回  12

注:两个参数均为同样月份的29号,所以返回一整数。

 
 months_between(to_date('1999.11.29','yyyy.mm.dd'), to_date('1998.12.24','yyyy.mm.dd'))

 返回   13.16129

Si la fecha dos momentos diferentes, incluso fuera de la diferencia dividida por la fecha 31, el resultado es un montón de cifras decimales.

    select months_between(to_date('01-31-2008','MM-DD-YYYY'),to_date('12-31-1998','MM-DD-YYYY')) "MONTHS" FROM DUAL;      
    1      
   select months_between(to_date('02-01-2008','MM-DD-YYYY'),to_date('12-31-1998','MM-DD-YYYY')) "MONTHS" FROM DUAL;      
    1.03225806451613 

 

Las funciones definidas por el procesamiento de diferencia mes

create or replace function fun_month_num (var_begin_date in varchar2,var_end_date in varchar2)  
return number  
as
    is_begin_date date;  
    is_end_date date;  
    is_count number(10);  
    i number(10);  
    j number(10);  
    is_this_date date;  
begin  
    is_begin_date := to_date(var_begin_date,'yyyy-mm-dd');  
    is_end_date := to_date(var_end_date,'yyyy-mm-dd');    
    is_this_date := last_day(is_end_date) ;    
    is_count := 0 ;  
   
    loop  
    exit when is_this_date < last_day(is_begin_date)+1 ;  
        is_count := is_count+1;                        
        is_this_date := last_day(is_this_date)-32;  

    end loop;  

    return is_count;  
end;

uso

select fun_month_num('2008-09-30','2008-02-01') from dual; 

 

Día siguiente()

NEXT_DAY fecha (fecha, char) a un parámetro de fecha

 fecha de la próxima semana de retorno, días 1-7 o el domingo - sábado, domingo 1 representa 
   1.234.567      
   Ri centenar de un solo de veinte-mil de tres de cuatro centenar de cincuenta por-de seis  

 next_day(sysdate,6)是从当前开始下一个星期五。
后面的数字是从星期日开始算起。    
select next_day(to_date('2014-4-1','yyyy-MM-dd'),'星期三') from dual;

从特定日期得到之后的第一个星期三的日期。

select next_day( sysdate, 'MONDAY') from dual;
可以求出当前日期的下个星期一。

next_day(to_date('1999.11.24','yyyy.mm.dd'),'friday')      
// 返回   1999年11月26日
//1999年11月24日是星期三,第二个参数是星期五,是两天后。

 

TO_CHAR formato de fecha ()

select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') as nowTime from dual;   //日期转化为字符串   
select to_char(sysdate,'yyyy') as nowYear   from dual;   //获取时间的年   
select to_char(sysdate,'mm')    as nowMonth from dual;   //获取时间的月   
select to_char(sysdate,'dd')    as nowDay    from dual;   //获取时间的日   
select to_char(sysdate,'hh24') as nowHour   from dual;   //获取时间的时   
select to_char(sysdate,'mi')    as nowMinute from dual;   //获取时间的分   
select to_char(sysdate,'ss')    as nowSecond from dual;   //获取时间的秒 

Obtiene el número de horas Comparación

  select sysdate ,to_char(sysdate,'hh') from dual;   
  //2003-10-13 19:35:21 07 
  select sysdate ,to_char(sysdate,'hh24') from dual;  
  //2003-10-13 19:35:21 19 

 

la trunc () función de procesamiento de Fecha

    Sintaxis: TRUNCAR (fecha [, FMT])

  En donde: Fecha de un valor de fecha, formato de fecha FMT.

    La fecha será la fecha especificada formato de intercepción; ignorados por la fecha más reciente interceptado.

 select trunc(sysdate) from dual;--2017/2/13,返回当前时间
   select trunc(sysdate,'yy') from dual;--2017/1/1,返回当年第一天
   select trunc(sysdate,'mm') from dual;--2017/2/1,返回当月的第一天
   select trunc(sysdate,'d') from dual;--2017/2/12,返回当前星期的第一天,即星期天
   select trunc(sysdate,'dd') from dual;--2017/2/13,返回当前日期,今天是2017/2/13
   select trunc(sysdate ,'HH24') from dual;--2017/2/13 15:00:00,返回本小时的开始时间
   select trunc(sysdate ,'MI') from dual;--2017/2/13 15:13:00,返回本分钟的开始时间

   trunc(sysdate,'year') YEAR,        //返回当前年的1月1日,无时分秒 
   trunc(sysdate,'month') MONTH ,     //返回当前月的1日,无时分秒 
   trunc(sysdate,'day') DAY           //返回当前星期的星期天,无时分秒 

对number类型则截取小数,截取时并不对数据进行四舍五入。
    select trunc(123.567,2) from dual;--123.56,将小数点右边指定位数后面的截去;
    select trunc(123.567,-2) from dual;--100,第二个参数可以为负数,表示将小数点左边指定位数后面的部分截去,即均以0记;
    select trunc(123.567) from dual;--123,默认截去小数点后面的部分;

 

extracto () la función de interceptación de intervalo desde el tipo de fecha o tipos a una parte específica;

select extract(year from sysdate) from dual;
select extract(month from sysdate) from dual;
select extract(day from sysdate) from dual;
select extract(Hour from systimestamp) from dual;
select extract(minute from systimestamp) from dual;
select extract(second from systimestamp) from dual;
select extract(timezone_hour from systimestamp) th from dual;
select extract(timezone_minute from systimestamp) tm from dual;
select extract(timezone_region from systimestamp) tr from dual;
select extract(timezone_abbr from systimestamp) ta from dual;

tiempo específico entre las dos fechas, puede extraer función ();

select extract(day from dt2-dt1) day
,extract(hour from dt2-dt1) hour
,extract(minute from dt2-dt1) minute
,extract(second from dt2-dt1) second
from
( select to_timestamp('2013-02-04 15:07:00','yyyy-mm-dd hh24:mi:ss') dt1,to_timestamp('2013-11-30 22:08:46', 'yyyy-mm-dd hh24:mi:ss') dt2 from dual
);

 

ronda [redondeado a la fecha más cercana] (día: redondeado al domingo más cercano). Y la diferencia es trunc, trunc () no se realiza la operación de redondeo, única intercepción

   select sysdate S1, 
   round(sysdate) S2 , 
   round(sysdate,'year') YEAR, 
   round(sysdate,'month') MONTH , 
   round(sysdate,'day') DAY from dual

 

mayor lista de la vuelta de la última fecha

 select greatest('01-1月-04','04-1月-04','10-2月-04') from dual

 

conversión de la fecha de Oracle

oráculo cálculo de horas, minutos, segundos, milisegundos      

    select      
     Days,      
     A,      
     TRUNC(A*24) Hours,      
     TRUNC(A*24*60 - 60*TRUNC(A*24)) Minutes,      
     TRUNC(A*24*60*60 - 60*TRUNC(A*24*60)) Seconds,      
     TRUNC(A*24*60*60*100 - 100*TRUNC(A*24*60*60)) mSeconds      
    from      
    (      
     select      
     trunc(sysdate) Days,      
     sysdate - trunc(sysdate) A      
     from dual      
   )    

Oracle fecha de cálculo de conversión

  floor((date2-date1) /365) 作为年      
   floor((date2-date1, 365) /30) 作为月      
   d(mod(date2-date1, 365), 30)作为日.
当前时间减去7分钟的时间 
select sysdate,sysdate - interval ’7’ MINUTE from dual 
当前时间减去7小时的时间 
select sysdate - interval ’7’ hour from dual 
当前时间减去7天的时间 
select sysdate - interval ’7’ day from dual 
当前时间减去7月的时间 
select sysdate,sysdate - interval ’7’ month from dual 
当前时间减去7年的时间 
select sysdate,sysdate - interval ’7’ year from dual 
时间间隔乘以一个数字 
select sysdate,sysdate - 8 *interval ’2’ hour from dual

Fecha día se convirtió al segundo

select (sysdate-to_date('2003-12-03 12:55:45','yyyy-mm-dd hh24:mi:ss'))*24*60*60 from dual 

 

Publicados 370 artículos originales · ganado elogios 88 · vistas 290 000 +

Supongo que te gusta

Origin blog.csdn.net/qq_35029061/article/details/100117567
Recomendado
Clasificación