简体   繁体   English

获取正确的日期选择器格式

[英]Getting the correct format of the datepicker

I have a column inside of my datebase that stores a date that user pick when they offer a job. 我的数据库中有一个列,用于存储用户提供工作时选择的日期。 It's currently formed in this way: "Fri Feb 15 2019". 目前以这种方式形成:“ 2019年2月15日星期五”。

I want to be able to compare it to the current date which is formed as: "2019-01-27" 我希望能够将其与当前日期进行比较,其格式为:“ 2019-01-27”

I'm guessing that the best way to do this would be to transform the datepicker format to the date one, and then compare them. 我猜想最好的方法是将日期选择器格式转换为日期格式,然后进行比较。 This is the code that I have for the date picker currently when someone registeres. 这是当有人注册时当前用于日期选择器的代码。

<div class="form-group">                                             
<label for="location" class="control-label">DATE</label>                                                         
<input type="text" id="datepicker" class="form-control" placeholder="Pick a 
date" name="datepicker">                                             
</div>
   <script>
    var picker = new Pikaday({ field: document.getElementById('datepicker') }); 
    </script>




I would suggest using the javascript plugin called Momentjs. 我建议使用名为Momentjs的JavaScript插件。 It allows for easy formatting of dates, without the base javascript hassle. 它可以轻松格式化日期,而无需担心基本的javascript麻烦。

Add this to your HTML, near the bottom of your page, but before your script tags: 将其添加到HTML中,靠近页面底部,但位于脚本标签之前:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>

Then to format your datepicker value, inside your script, use: 然后在脚本中格式化日期选择器的值,请使用:

var myDate = moment(picker.value).format('YYYY-MM-DD'); 

Here is the Momentjs documentation: Momentjs Docs 这是Momentjs文档: Momentjs文档

Open the example in full page : 全页打开示例:

Use new Date and then you can extract the day the month and the year 使用new Date ,然后你可以提取daymonthyear

and to compare with another date, you can just new Date("2006-05-1").getMonth() === new Date("2006-05-2").getMonth() && ... 并与另一个日期进行比较,您可以将new Date("2006-05-1").getMonth() === new Date("2006-05-2").getMonth() && ...

 var picker = new Pikaday({ field: document.getElementById('datepicker') }); const dateInput = document.getElementById('datepicker'); function handleChange() { const date = new Date(dateInput.value), formattedDate = `${date.getFullYear()}-${date.getMonth()+1}-${date.getDate()}`; console.log(formattedDate) } dateInput.addEventListener("change", handleChange); 
 <script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css"> <input type="text" id="datepicker"> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM