前端练手小项目--自定义时间(html+css+js)

news2024/9/17 7:23:46

自定义时间

写文章的因

关于要写这篇文章的原因

  • 是记录在工作上遇到的困难需求,
  • 是希望能给大家提供一些解决问题的思路

接下来我描述这个需求的多样性,难点在哪。

  • 勾选勾选框开始时间与结束时间默认显示昨天与今天。
  • 取消勾选框开始时间与结束时间清空。
  • 选择开始时间,勾选框勾选,结束时间为今天。
    在用户点击 开始时间大于或者等于结束时间时,
    提示错误信息,开始时间清空,
    选择结束时间时,小于或者等于开始时间,
    显示报错,结束时间清空。
  • 选择结束时间,勾选框勾选,开始时间
    为所选结束时间的昨天。
    在用户点击结束时间小于或者等于结束时间时,
    提示错误信息,结束时间清空,
    选择开始时间时,大于或者等于开始时间,
    显示报错,开始时间清空。
  • 其次在每次选择时间的时候都要计算出开始时间与结束时间。
  • 用户不能选择限制范围之外的时间

请添加图片描述

1.效果演示

自定义时间效果展示

2.思路解析

2.1编写html

该部分比较简单,就一个错误提示div
一段文字,一个勾选框,两个时间选择框

<div id="errorMsg" style="color:red;margin-top:10px;margin-bottom:20px"></div>
    <div>
        <label for="select_time">自定义文件修改时间:</label>
        <input type="checkbox" name="select_time" id='selectTime' 
        	onchange="changeStatus(event)" id="selectTime">
        <input type="date"  id='startTime' ref="startTime" 
        	onchange="getstartTime(event)" max=""> ---
        <input type="date" ref="endTime" id="endTime" 
        	onchange="getEndTime(event)" max="">
    </div>

2.2编写自动得到当前时间的函数

这里的难点是在日期框显示‘yyyy-mm-dd’,
就需要对获取到的值进行处理,

 function GetDateStr(AddDayCount) { 
     var dd = new Date(); 
         dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期 
     var y = dd.getFullYear(); 
     var m = (dd.getMonth()+1);//获取当前月份的日期 
     var d = dd.getDate(); 
     if(m>=10&&m>=10){
          return y+"-"+m+"-"+d; 
      }else if(m<10&&d>=10){
          return y+"-"+'0'+m+"-"+d; 
      }else if(m<10&&d<10){
          return y+"-"+'0'+m+"-"+'0'+d; 
          } 
    }

2.3限制用户选择日期

该功能通过给input添加一个max属性即可,
但是该max属性值必须是max='yyyy-mm-dd’的形式。

window.onload=function(){
    document.getElementById('startTime').setAttribute('max',this.GetDateStr(-1))
    document.getElementById('endTime').setAttribute('max',this.GetDateStr(0))    
}

2.4关于时间的计算

时间的计算问题,因为我们通过Date.parse()
格式化时间得到的时间是东八区的时间,要想得到
零点的时间需要减去8个小时。
开始时间等于start=Date.parse(‘yyyy-mm-dd’)/1000-83600
结束时间等于end=Date.parse(‘yyyy-mm-dd’)/1000+16
3600
因为我们需要的时间是昨天的零点,以及今天的24点

  //得到时间为s
 var  modification_time_start=null,
      modification_time_end=null,
  modification_time_start=Date.parse(this.GetDateStr(-1)) / 1000-8*3600
  modification_time_end=Date.parse(this.GetDateStr(0)) / 1000+16*3600  

2.5用户选择开始时间

当用户选择开始时间,结束时间调用 GetDateStr()并赋值。
勾选框勾选,给该元素设置属性checked为true。
然后就是对开始时间与结束时间的判断来决定
是否显示错误提示,以及清空开始框。

function getstartTime() {
    $('#selectTime').attr('checked',true)//给勾选框添加属性,让其处于勾选状态
    $('#selectTime').prop('checked',true)
    modification_time_start = Date.parse($('#startTime').val())/1000-8*3600
    // 用户只选中开始时间,结束时间默认为当前时间。并重新赋值
    if(count||modification_time_end===null){
        document.getElementById('endTime').value=this.GetDateStr(0)
        count=!count
      }
    if(document.getElementById('startTime').value ==='' 
    		&& document.getElementById('endTime').value===''){
           $('#selectTime').attr('checked',false)
            $('#selectTime').prop('checked',false)
       }
    // document.getElementById('endTime').value=this.GetDateStr(0)
    document.getElementById('startTime').value=$('#startTime').val()
    modification_time_end= Date.parse($('#endTime').val())/1000+16*3600
    if(modification_time_end<=modification_time_start || 
    		$('#endTime').val()<=$('#startTime').val()){
       //alert('所选时间大于结束时间,请重新选择时间')
       document.getElementById('errorMsg').innerText='所选时间大于或等于结束时间,请重新选择时间'
       document.getElementById('startTime').value=''
       document.getElementById('endTime').value=$('#endTime').val()
     }else{
         document.getElementById('errorMsg').innerText=''
         }
        console.log('开始时间===》',modification_time_start,'结束时间===》', modification_time_end)
    }

2.6用户选择开始时间

当用户选择结束时间,结束时间调用 GetDateStr()并赋值。
勾选框勾选,给该元素设置属性checked为true。
然后就是对开始时间与结束时间的判断来决定
是否显示错误提示,以及清空结束时间框。

 function getEndTime() {
                $('#selectTime').attr('checked',true)
                $('#selectTime').prop('checked',true)      
                modification_time_end = Date.parse($('#endTime').val())/1000+16*3600
                document.getElementById('endTime').value=$('#endTime').val()
                modification_time_start= Date.parse($('#startTime').val())/1000-8*3600
            if(document.getElementById('startTime').value ==='' && document.getElementById('endTime').value===''){
                $('#selectTime').attr('checked',false)
                $('#selectTime').prop('checked',false)
        }
                //当用户只选中最后时间时,开始时间应该有个默认值。该最后时间的前一天,重新给开始时间赋值 
             if(modification_time_end<=modification_time_start || $('#endTime').val()<=$('#startTime').val()){
                        //alert('所选时间小于开始时间,请重新选择时间')
                        document.getElementById('errorMsg').innerText='所选时间小于或等于开始时间,请重新选择时间'
                        document.getElementById('endTime').value=''
                        document.getElementById('startTime').value=$('#startTime').val()
             }else{
                    document.getElementById('errorMsg').innerText=''
                }
             if(count){
                    let date=new Date(Date.parse($('#endTime').val())-24*3600*1000)
                    Y = date.getFullYear() + '-'
                    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
                    D = (date.getDate()< 10 ? '0'+date.getDate() : date.getDate())
                    document.getElementById('startTime').value=Y+M+D
                    modification_time_start=Date.parse(Y+M+D)/1000-8*3600
                    count=!count
            }
            console.log('开始时间===》',modification_time_start,'结束时间===》', modification_time_end)
        }

2.7总结

在该需求中,我们学到了那些内容

  • 计算时间的准确性(开始时间的0点,结束时间的24点)以及关于使用Date.parse(‘yyyy-mm-dd’)的值为东八区的值。
    +怎么得到当前时间,以及怎么将该值赋值到日期框中document.getElementById(‘startTime’).value=‘yyyy-mm-dd’,
  • 通过jquery改变勾选框的勾选状态$(’#selectTime’).attr(‘checked’,true) $(’#selectTime’).prop(‘checked’,true)

3.完整代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.4/jquery.js"></script>
</head>
<body>
    <div id="errorMsg" style="color:red;margin-top:10px;margin-bottom:20px"></div>
    <div>
        <label for="select_time">自定义文件修改时间:</label>
        <input type="checkbox" name="select_time" id='selectTime' onchange="changeStatus(event)" id="selectTime">
        <input type="date"  id='startTime' ref="startTime" onchange="getstartTime(event)" max=""> ---
        <input type="date" ref="endTime" id="endTime" onchange="getEndTime(event)" max="">
    </div>
    <script>
         var  modification_time_start=null,
         modification_time_end=null,
         count=true

    function GetDateStr(AddDayCount) { 
                var dd = new Date(); 
                dd.setDate(dd.getDate()+AddDayCount);//获取AddDayCount天后的日期 
                var y = dd.getFullYear(); 
                var m = (dd.getMonth()+1);//获取当前月份的日期 
                var d = dd.getDate(); 
                if(m>=10&&m>=10){
                    return y+"-"+m+"-"+d; 
                }else if(m<10&&d>=10){
                    return y+"-"+'0'+m+"-"+d; 
                }else if(m<10&&d<10){
                    return y+"-"+'0'+m+"-"+'0'+d; 
                } 
           }
    window.onload=function(){
        document.getElementById('startTime').setAttribute('max',this.GetDateStr(-1))
        document.getElementById('endTime').setAttribute('max',this.GetDateStr(0))    
    }
    function changeStatus(event) {
                if (event.target.checked) {
                    modification_time_start=Date.parse(this.GetDateStr(-1)) / 1000-8*3600
                    modification_time_end=Date.parse(this.GetDateStr(0)) / 1000+16*3600
                    document.getElementById('startTime').value = this.GetDateStr(-1)
                    document.getElementById('endTime').value = this.GetDateStr(0)
                    console.log('开始时间===》',modification_time_start,'结束时间===》', modification_time_end)
                }else{
                    document.getElementById('startTime').value =null
                    document.getElementById('endTime').value=null
                    modification_time_end=null
                    modification_time_start=null
                }
            }
    function getstartTime() {
                $('#selectTime').attr('checked',true)
                $('#selectTime').prop('checked',true)
                modification_time_start = Date.parse($('#startTime').val())/1000-8*3600
                // 用户只选中开始时间,结束时间默认为当前时间。并重新赋值
                 if(count||modification_time_end===null){
                    document.getElementById('endTime').value=this.GetDateStr(0)
                    count=!count
                }
                if(document.getElementById('startTime').value ==='' && document.getElementById('endTime').value===''){
                    $('#selectTime').attr('checked',false)
                     $('#selectTime').prop('checked',false)
                }
                // document.getElementById('endTime').value=this.GetDateStr(0)
                document.getElementById('startTime').value=$('#startTime').val()
                modification_time_end= Date.parse($('#endTime').val())/1000+16*3600
                if(modification_time_end<=modification_time_start || $('#endTime').val()<=$('#startTime').val()){
                        //alert('所选时间大于结束时间,请重新选择时间')
                        document.getElementById('errorMsg').innerText='所选时间大于或等于结束时间,请重新选择时间'
                        document.getElementById('startTime').value=''
                        document.getElementById('endTime').value=$('#endTime').val()
                }else{
                    document.getElementById('errorMsg').innerText=''
                }
                console.log('开始时间===》',modification_time_start,'结束时间===》', modification_time_end)
            }
    function getEndTime() {
                $('#selectTime').attr('checked',true)
                $('#selectTime').prop('checked',true)      
                modification_time_end = Date.parse($('#endTime').val())/1000+16*3600
                document.getElementById('endTime').value=$('#endTime').val()
                modification_time_start= Date.parse($('#startTime').val())/1000-8*3600
            if(document.getElementById('startTime').value ==='' && document.getElementById('endTime').value===''){
                $('#selectTime').attr('checked',false)
                $('#selectTime').prop('checked',false)
        }
                //当用户只选中最后时间时,开始时间应该有个默认值。该最后时间的前一天,重新给开始时间赋值 
             if(modification_time_end<=modification_time_start || $('#endTime').val()<=$('#startTime').val()){
                        //alert('所选时间小于开始时间,请重新选择时间')
                        document.getElementById('errorMsg').innerText='所选时间小于或等于开始时间,请重新选择时间'
                        document.getElementById('endTime').value=''
                        document.getElementById('startTime').value=$('#startTime').val()
             }else{
                    document.getElementById('errorMsg').innerText=''
                }
             if(count){
                    let date=new Date(Date.parse($('#endTime').val())-24*3600*1000)
                    Y = date.getFullYear() + '-'
                    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-'
                    D = (date.getDate()< 10 ? '0'+date.getDate() : date.getDate())
                    document.getElementById('startTime').value=Y+M+D
                    modification_time_start=Date.parse(Y+M+D)/1000-8*3600
                    count=!count
            }
            console.log('开始时间===》',modification_time_start,'结束时间===》', modification_time_end)
        }
    </script>
</body>
</html>

好了这次的文章就到这了
如果觉得还不错的话,帮忙点个关注吧
希望能给博主点赞哎🎨,评论🧶,收藏🥼三连一波加粗样式

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/888845.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

element+vue 表格行拖拽功能

解决方案 使用 sortable.js 步骤一&#xff1a; 安装 npm install vuedraggable步骤二&#xff1a;引入 import Sortable from sortablejs;步骤三&#xff1a; el-table 添加row-key属性&#xff0c;外层包一层 sortableDiv <div class"sortableDiv"> 拖…

IDEA【java.sql.SQLSyntaxErrorException: ORA-00904: “P“.“PRJ_NO“: 标识符无效】

IDEA报错如下&#xff1a; 2023-08-17 11:26:15.535 ERROR [egrant-biz,b48324d82fe23753,b48324d82fe23753,true] 24108 --- [ XNIO-1 task-1] c.i.c.l.c.RestExceptionController : 服务器异常org.springframework.jdbc.BadSqlGrammarException: ### Error queryin…

Docker 的基本概念和优势,在应用程序开发中的实际应用。

Docker是一个开源的容器化平台&#xff0c;让开发者能够轻松地打包、运输和运行应用程序。其基本概念包括&#xff1a; 镜像(Image)&#xff1a;一个镜像是一个只读的软件包&#xff0c;它包含了运行应用所需的所有代码、库文件、环境变量和配置文件等。 容器(Container)&…

docker之简介与安装

环境配置问题 没有虚拟机&#xff0c;我们往往是打包代码发给对方&#xff0c;然后让对方安装相应的环境&#xff0c;比如node、数据库&#xff0c;要是配置不同&#xff0c;项目很有可能无法运行&#xff0c;还会报错&#xff0c;如果多个人想要运行这份代码&#xff0c;那还得…

手撸一个简单的Tomcat,延伸`SpringMvc`的原理

为什么写这篇文章 一直以来都说tomcat是用的java写的&#xff0c;但是也是不明白到底是怎么弄的&#xff0c;最近有个机会搞明白了&#xff0c;特此记录&#xff0c;可以使得更懂tomcat的原理 用java写一个java的运行程序&#xff0c;听着就很酷&#xff0c;你觉得呢&#xf…

多模态分割医学数据集小调研

QaTa-COV19 V1&#xff1a; 该数据集由4603张COVID-19胸部x光片组成;该数据集首次包含了用于COVID-19感染区域分割任务的真值分割掩码。加上对照组的胸部x光片&#xff0c;QaTa-COV19由120,968张图像组成。图像位于“QaTa-COV19/ images /”文件夹下&#xff0c;ground-truth分…

selector.replaceAll is not a function报错问题

个人项目地址&#xff1a; SubTopH前端开发个人站 &#xff08;自己开发的前端功能和UI组件&#xff0c;一些有趣的小功能&#xff0c;感兴趣的伙伴可以访问&#xff0c;欢迎提出更好的想法&#xff0c;私信沟通&#xff0c;网站属于静态页面&#xff09; SubTopH前端开发个人站…

Leetcode49. 字母异位词分组

给你一个字符串数组&#xff0c;请你将 字母异位词 组合在一起。可以按任意顺序返回结果列表。 字母异位词 是由重新排列源单词的所有字母得到的一个新单词。 解题思路&#xff1a;计数 思路&#xff1a;题意是字符串的字符都是小写&#xff0c;可以对每个字符串统计其中字符的…

什么是公网、私网、内网、外网?

中午好&#xff0c;我的网工朋友。 最近经常有很多小白朋友在问&#xff0c;公网、私网、内网、外网&#xff0c;这些的概念是啥样的&#xff0c;又该怎么去界定。 关于IP地址&#xff0c;确实没有太明确的区分&#xff0c;其实也不必太过咬文嚼字。 内网、外网就是一个参考…

SAP复杂表格转换为JASON格式的例子

分享一个三层表格转换伙JASON格式的例子&#xff0c;代码如下。 REPORT zjason_test. "// 定义 DATA: lv_json TYPE string.DATA: BEGIN OF ls_detail_l3,code_l3 TYPE string,name_l3 TYPE string,age_l3 TYPE string,END OF ls_detail_l3,lt_detail_l3 LIKE TABLE OF…

SSO单点登录(SpringSecurity OAuth2.0 redis mysql jwt)

SSO单点登录 什么是单点登录 SSO(Single Sign On) 在多系统架构中&#xff0c;用户只需要一次登录就可以无需再次登录(比如你在打开淘宝之后点击里边的天猫) 在以前我们的单系统中,用户如果登录多个服务需要多次登录&#xff0c;实现单点登录之后&#xff0c;可以实现一次登录…

Qt:隐式内存共享

隐式内存共享 Many C classes in Qt use implicit data sharing to maximize resource usage and minimize copying. Implicitly shared classes are both safe and efficient when passed as arguments, because only a pointer to the data is passed around, and the data i…

K8s实战4-使用Helm在Azure上部署Ingress-Nginx和Tokengateway

手动发布Ingress-Nginx 1 登录到aks(dfinder-gw-aks) az login az account set --subscription ${sub ID} az aks get-credentials --resource-group ${groupname} --name ${aks name} 2 下载 ingress-nginx-4.2.5.tgz curl -LO https://github.com/kubernetes/ingress-ngi…

Hyper-V增加桥接网络设置(其他方式类同)

点击连接到的服务器&#xff0c;右单击或者右边点击“虚拟交换机管理器” 选择网络种类 配置虚拟交换机信息 外部网络选择物理机网卡设备

CS1988|C#无法在异步方法中使用ref,in,out类型的参数的问题

CS1988|C#无法在异步方法中使用ref,in,out类型的参数 &#x1f300;|场景&#xff1a; BlazorServer的场景中推荐使用异步方法&#xff0c;使用ref,out,in为参数前缀则报错CS1988 原因如下: ref parameters are not supported in async methods because the method may not h…

torch模型转onnx

加载模型 modeltorch.load(saved_model/moudle_best_auc.pth, map_locationcpu) model.eval().cpu()注&#xff1a;由于导出的模型是用于推理的&#xff0c;因此必须指定模型加载的位置和模型验证的位置&#xff0c;这里我使用了cpu做出导出的硬件 分析模型的输入和输出 这里…

基于SSH框架实现的管理系统(包含java源码+数据库)

资料下载链接 介绍 基于SSH框架的管理系统 简洁版 &#xff1b; 实现 登录 、 注册 、 增 、 删 、 改 、 查 &#xff1b; 可继续完善增加前端、校验、其他功能等&#xff1b; 可作为 SSH&#xff08;Structs Spring Hibernate&#xff09;项目 开发练习基础模型&#xf…

维护平衡的艺术:如何与干系人建立和谐关系以确保项目成功

在项目管理领域中&#xff0c;干系人的作用是无法忽视的。他们的支持和参与往往是项目成功的关键。与干系人建立和维护良好的关系成为每一位项目经理必备的技能。接下来&#xff0c;我们将深入探讨如何有效地与干系人互动&#xff0c;从而为项目的成功奠定坚实基础。 干系人的…

中国“诺贝尔奖”未来科学大奖公布2023年获奖名单

未来科学大奖委员会于8月16日公布2023年获奖名单。柴继杰、周俭民因发现抗病小体并阐明其结构和在抗植物病虫害中的功能做出的开创性工作获得“生命科学奖”&#xff0c;赵忠贤、陈仙辉因对高温超导材料的突破性发现和对转变温度的系统性提升所做出的开创性贡献获得“物质科学奖…

2023骨传导耳机推荐,适合运动骨传导耳机推荐

相信很多人跟我一样&#xff0c;随着现在五花八门的耳机品种增多&#xff0c;选耳机的时候真是眼花缭乱&#xff0c;尤其还是网购&#xff0c;只能看&#xff0c;不能试&#xff0c;所以选择起来比较困难&#xff0c; 作为一个运动达人&#xff0c;为了让大家在购买耳机时少走弯…