-
-
Save AvgustPol/8b279565aa476a0f0ff010662f27bb07 to your computer and use it in GitHub Desktop.
Set Current DateTime to input using JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
c# model | |
public DateTime DateTime { get; set; } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Razor | |
/// form code /// | |
<input asp-for="Model.Input.DateTime" class="form-control" /> | |
/// form code /// |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
JS | |
// Inp | |
<script> | |
$.fn.setNow = function (onlyBlank) { | |
var now = new Date($.now()) | |
, year | |
, month | |
, date | |
, hours | |
, minutes | |
, seconds | |
, formattedDateTime | |
; | |
year = now.getFullYear(); | |
month = now.getMonth().toString().length === 1 ? '0' + (now.getMonth() + 1).toString() : now.getMonth() + 1; | |
date = now.getDate().toString().length === 1 ? '0' + (now.getDate()).toString() : now.getDate(); | |
hours = now.getHours().toString().length === 1 ? '0' + now.getHours().toString() : now.getHours(); | |
minutes = now.getMinutes().toString().length === 1 ? '0' + now.getMinutes().toString() : now.getMinutes(); | |
seconds = now.getSeconds().toString().length === 1 ? '0' + now.getSeconds().toString() : now.getSeconds(); | |
formattedDateTime = year + '-' + month + '-' + date + 'T' + hours + ':' + minutes + ':' + seconds; | |
if ( onlyBlank === true && $(this).val() ) { | |
return this; | |
} | |
$(this).val(formattedDateTime); | |
return this; | |
} | |
$(function () { | |
// Handler for .ready() called. | |
$('input[type="datetime-local"]').setNow(); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Inspired by "HTML5 Input datetime-local default value of today and current time"