This question may be a bit challenging :
How to use JavaScript to change input type="date" format to :YYYY-MM-DD and no matter which date the user chooses ,the date need always be converted to the last day of the Month.
For example if the user choose 2023-06-01 ,then in the final the date should be :
2023-06-30
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Test</title>
</head>
<style media="screen">
.form-question {
display: flex;
flex-direction: column;
justify-content: center;
margin: 0 0 3rem;
min-height: 3rem;
}
.form-question__title {
color: #342357;
font-size: 1.5rem;
padding: 1rem;
}
.input-container {
border-bottom: solid 2px #333333;
}
.input-container input {
border: none;
box-sizing: border-box;
outline: 0;
padding: .75rem;
width: 100%;
}
</style>
<body>
<div class="form-question">
<div class="form-question__title">
<span>Effective Date</span>
</div>
<div class="input-container">
<input id="effective-date" type="date" name="effective-date" minlength="1" maxlength="64" placeholder=" " autocomplete="nope" required="required"></input>
<span class="bar"></span>
</div>
</div>
</body>
</html>
Any friend can help ?
3
Answers
Base on this idea, You can try this:
To get the last day of the month you can pass the next month, with day 0 to
Date()
it should roll back to the last day of previous month. To to format the date you can usetoLocaleDateString
with Swedish locale. To display it in UI, you can make an overlay span that covers original input.Unfortunately it’s not possible to change the visual representation of the date. This is determined by the locale of your system. Though the output will always be the same (ISO 8601) format.
You can read the value of the date input as a
Date
object with thevalueAsDate
property. This object can be manipulated. Add1
to the current month and set the current date to0
. The value1
would represent the first date of the month,0
represents one day less, which is the last day of the previous month.