0

I am getting date as 20150211, but I want to display it like '2015-02-11' using jquery or any other way.

I tried below code in .cshtml :

foreach (var item in ViewBag.Stats)
{
    <span class="visitDate">@item.ItemArray[0]</span>
}

<script type="text/javascript">
    $(document).ready(function () {            
        $(".visitDate").text().replace(/\s+/g, '-').toLowerCase();
    });
</script>
ekad
  • 14,436
  • 26
  • 44
  • 46
  • Jquery doesn't have any parsing methods? I think it has. Just parse this to `datetime` or `date` (whatever it called in jquery) and format this date instead of string replacing? – Soner Gönül Feb 25 '15 at 12:13
  • Worth looking at https://github.com/phstc/jquery-dateFormat maybe? – Dr Schizo Feb 25 '15 at 12:13
  • possible duplicate of [jQuery date formatting](http://stackoverflow.com/questions/5250244/jquery-date-formatting) –  Feb 25 '15 at 12:38

3 Answers3

0

This should work (assuming you are setting the visit date text to the new format):

var parts = [ text.slice(0, 4), text.slice(4, 6), text.slice(6, 8) ];
$(".visitDate").text(parts.join("-"))

Or in C#:

<span class="visitDate">
@{ 
    var date = DateTime.ParseExact(item.ItemArray[0], "yyyyMMdd", null);
    <text>@date.ToString("yyyy-MM-dd")</text>
}
</span>
Dhunt
  • 1,584
  • 9
  • 22
  • this is useful : @{ var date = DateTime.ParseExact(item.ItemArray[0], "yyyyMMdd", null); @date.ToString("yyyy-MM-dd") } : thanks – Sjm Kaushik Feb 25 '15 at 13:03
0

convert string into date-time and then display it in format

@{
   DateTime date;

   if (DateTime.TryParseExact(item.ItemArray[0],
                               "yyyyMMdd", 
                               System.Globalization.CultureInfo.InvariantCulture,
                               System.Globalization.DateTimeStyles.None, 
                               out date))
    {
      <span class="visitDate">date.ToString("yyyy-MM-dd",CultureInfo.InvariantCulture))</span>            //valid
    }
}
111
  • 1,779
  • 1
  • 12
  • 15
0

The easiest way is using moment.js.

You can get this lib by run npm command: npm install moment --save or by bower bower install moment --save After add this lib to your page. You can use:

moment("20161001", "YYYYMMDD").format("DD-MM-YYYY")

Hope this help.

Linh Nguyen Vu
  • 291
  • 4
  • 6