最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Convert input type text into date format - Stack Overflow

programmeradmin5浏览0评论

I have one input type text:

 <input type="text" id="policyholder-dob" name="policyholder-dob" />

I want to type number in this field in mm/dd/yyyy format: like 01/01/2014 This is my js code but its not working, what mistake have I made?

function dateFormatter(date) {
  var formattedDate = date.getDate() +
    '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
  return formattedDate;
}

var nextduedate = $("#policyholder-dob").val();

var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);

$("#policyholder-dob").prop("value", todaydate);
<script src=".7.1/jquery.min.js"></script>
<input type="text" id="policyholder-dob" name="policyholder-dob" />

I have one input type text:

 <input type="text" id="policyholder-dob" name="policyholder-dob" />

I want to type number in this field in mm/dd/yyyy format: like 01/01/2014 This is my js code but its not working, what mistake have I made?

function dateFormatter(date) {
  var formattedDate = date.getDate() +
    '/' + (date.getMonth() + 1) + '/' + date.getFullYear();
  return formattedDate;
}

var nextduedate = $("#policyholder-dob").val();

var dateFormatDate = nextduedate.slice(0, 2);
var dateFormatMonth = nextduedate.slice(2, 4);
var dateFormatYear = nextduedate.slice(4, 8);
var totalFormat = dateFormatMonth + '/' + dateFormatDate + '/' + dateFormatYear;
var againNewDate = new Date(totalFormat);
againNewDate.setDate(againNewDate.getDate() + 1);
var todaydate = dateFormatter(againNewDate);

$("#policyholder-dob").prop("value", todaydate);
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<input type="text" id="policyholder-dob" name="policyholder-dob" />

Any help will be really appreciated.

Share Improve this question edited Jan 10 at 11:23 Naeem Akhtar 1,2701 gold badge12 silver badges23 bronze badges asked Mar 1, 2014 at 5:03 supersaiyansupersaiyan 1,7306 gold badges16 silver badges37 bronze badges 3
  • Related: stackoverflow./questions/5619202/… – Charlie Commented Mar 1, 2014 at 5:11
  • no i dont think its meet my requirement if i am tying any digit its giving some date format.. – supersaiyan Commented Mar 1, 2014 at 5:20
  • 2 What's not working? Do you have a jsFiddle? – Xotic750 Commented Mar 1, 2014 at 5:51
Add a ment  | 

4 Answers 4

Reset to default 0

Thankfully, your input is consistently in this format:

mm/dd/yyyy

So you can convert it to a Date object through a custom function, such as:

function stringToDate(str){
    var date = str.split("/"),
        m = date[0],
        d = date[1],
        y = date[2],
        temp = [];
    temp.push(y,m,d);
    return (new Date(temp.join("-"))).toUTCString();
}

Or:

function stringToDate(str){
    var date = str.split("/"),
        m = date[0],
        d = date[1],
        y = date[2];
    return (new Date(y + "-" + m + "-" + d)).toUTCString();
}

Etc..

Calling it is easy:

stringToDate("12/27/1963");

And it will return the correct timestamp in GMT (so that your local timezone won't affect the date (EST -5, causing it to be 26th)):

Fri, 27 Dec 1963 00:00:00 GMT //Late december

Example

There are various ways to acplish this, this is one of them.

I'd suggest moment.js for date manipulation. You're going to run into a world of hurt if you're trying to add 1 to month. What happens when the month is December and you end up with 13 as your month. Let a library handle all of that headache for you. And you can create your moment date with the string that you pull from the val. You substrings or parsing.

var d = moment('01/31/2014');                 // creates a date of Jan 31st, 2014
var duration = moment.duration({'days' : 1}); // creates a duration object for 1 day
d.add(duration);                              // add duration to date
alert(d.format('MM/DD/YYYY'));                // alerts 02/01/2014

Here's a fiddle showing it off.

Fortunately we now (2023) have <input type="date"> and Intl.DateTimeFormat that removes the need for manual parsing and formatting.

By default this will use the ordering (mm/dd/yyyy or dd/mm/yyyy) and separator (mm/dd/yyyy or mm-dd-yyyy) based on the user's locale

const dateFormat = new Intl.DateTimeFormat({
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
});

document
  .getElementById('date')
  .addEventListener('change', (e) => {
    var selectedDate = new Date(e.target.value);
    var formattedDate = dateFormat.format(selectedDate);
    console.log(formattedDate);
  });
<input type="date" id="date"></input>

To use a specific locale for the the output, pass it to the DateTimeFormat constructor. e.g. for dd/mm/yyyy use en-US

const dateFormatter = new Intl.DateTimeFormat('en-us', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
});

There's a minor issue with phuzi's response: it doesn't have proper error handling.

For example, if you pick a date and get an output, the function seems fine. But if you click on the month or day and type a 0, you'll get an error during date formatting. I redesigned the flow to be more functional, with guard clauses and better error handling.

Also, <input> elements are void elements. Some people call them "self-closing tags" because of XML conventions, but that's not really accurate for HTML.

const dateFormat = new Intl.DateTimeFormat('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
});

const isValidDate = (date) => date instanceof Date && !isNaN(date);

const parseDate = (dateStr) => {
  const date = new Date(dateStr);
  return isValidDate(date) ? date : null;
};

const formatDate = (date) => isValidDate(date) ? dateFormat.format(date) : null;

const parseAndFormatDate = (dateStr) => {
  const parsedDate = parseDate(dateStr);
  return parsedDate ? formatDate(parsedDate) : null;
};

const onChange = (e) => {
  const formattedDate = parseAndFormatDate(e.target.value);
  if (!formattedDate) {
    console.error('Invalid date input.');
    return;
  }
  console.log(formattedDate);
};

document.getElementById('date').addEventListener('change', onChange);
<input type="date" id="date">

发布评论

评论列表(0)

  1. 暂无评论