Skip to content

Instantly share code, notes, and snippets.

@AvgustPol
Created March 14, 2019 17:14
Show Gist options
  • Save AvgustPol/8b279565aa476a0f0ff010662f27bb07 to your computer and use it in GitHub Desktop.
Save AvgustPol/8b279565aa476a0f0ff010662f27bb07 to your computer and use it in GitHub Desktop.
Set Current DateTime to input using JavaScript
c# model
public DateTime DateTime { get; set; }
Razor
/// form code ///
<input asp-for="Model.Input.DateTime" class="form-control" />
/// form code ///
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>
@AvgustPol
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment