mike_pl
mike_pl

Reputation: 121

Javascript convert date string to DateTime type(C#) format issue

I am using jquery combodate which returns me a string with date like :

dateString = "12-07-2006"

In my Razor view I have:

 @Html.HiddenFor(m => m.BirthDate)   // BirthDate is a C# variable of type DateTime

What I want to do in my js code is:

   var dateString = $('#date').combodate('getValue');   // like:   "12-07-2006"

   document.getElementById('BirthDate').value = dateString; // format is wrong

So far I tried multiple examples looking for similar topics, but none of them works correctly.. I mean in my POST function after sending a form, i have ModelState error, that it is not valid value for DateTime variable (Date = {0001-01-01 00:00:00} - that i get in post method in backend code)

Upvotes: 1

Views: 834

Answers (3)

Dinca Adrian
Dinca Adrian

Reputation: 1230

maybe just do it manually without a library to understand more of this conversion you try to make.

dateString = "12-07-2006";
var parts = dateString.split('-');
//please put attention to the month (parts[0]), Javascript counts months from 0:
// January - 0, February - 1, etc

// parts[0] = 12 and represents the day
// parts[1] = 7 and represents the month
// parts[2] = 2006 and represents the year
var mydate = new Date(parts[2],parts[1]-1,parts[0]);

And now the mydate is a Date object that you can us in your model.

Upvotes: 0

Codesingh
Codesingh

Reputation: 3384

I would prefer you to use momentjs because you need date time format and it's the best way. momentjs allows parsing date with the specified time zone.

var momentDate = moment("2014-09-15 09:00:00");
and can access the JS date object via

momentDate ().toDate();

please refer http://momentjs.com/ for more formats.

Upvotes: 0

cringe
cringe

Reputation: 14010

From the combodate documentation:

All methods can be called as $(element).combodate('method', parameters).

Here is an example with combodate:

$(function(){
  var dateString = "12-07-2006"
  $('#BirthDate').combodate('setValue', dateString);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdn.rawgit.com/vitalets/combodate/master/src/combodate.js"></script>

<input type="text" id="BirthDate" data-format="DD-MM-YYYY" data-template="D MMM YYYY" name="date">

Upvotes: 1

Related Questions