bluray
bluray

Reputation: 1953

Javascript - parse locale datetime to us datetime format

Hello I would like to parse datetime from locale format to English format (for .NET REST API Server). I use jquery datetimepicker:

jQuery(document).ready(function () {
    'use strict';
    jQuery.datetimepicker.setLocale('cs');
    jQuery('#startDate').datetimepicker({
        format: 'd.m.Y H:i',
    });
});

<input ng-model="$ctrl.startDate" class="form-control" id="startDate" datetime-picker/>

In datetimepicker i have for example this date 10.01.2018 20:15 (10 January 2018) and I need to transform to 2018/01/10 20:15. This format is send to .NET server correctly. How to transform?

I need help with back way. I get date from server in this format: 2018-01-10T20:15:00 and i would like to show in datetimepicker in this format: 10.01.2018 20:15 How to transform this?

Thank you

Upvotes: 0

Views: 245

Answers (2)

synthet1c
synthet1c

Reputation: 6282

You could write a simple parser to get the components of your date string, then create a new Date and return the desired format.

const datestr = '10.01.2018 20:15'

// prepend zero if less than 10
const z = x => x > 9 ? x : '0' + x

// parse formatted date into server date
const parse = str => {
  const [day, month, year, hour, min] = str.split(/\.|\s|\:/)
  const date = new Date(year, month - 1, day, hour, min)
  const y = z(date.getFullYear())
  const m = z(date.getMonth() + 1)
  const d = z(date.getDate())
  const h = z(hour)
  const mn = z(min)
  return `${y}-${m}-${d}T${h}:${mn}:00`
}

console.log(
  parse(datestr)
)

Upvotes: 1

user3483203
user3483203

Reputation: 51155

With your conversion, you are trying to convert from a format which does not work across all browsers.

To accomplish this, you can split by a regex, in this case /\:|\s|\./g which splits by any ., : or whitespace. Then you can build your initial date again. Note that you will lose seconds, as you do not include seconds in your initial conversion.

var dateStr = '2018.01.10 08:15'
var arr = dateStr.split(/\:|\s|\./g)
var finalDate = arr[0] + '-' + arr[1] + '-' + arr[2] + 'T' + arr[3] + ':' + arr[4] + ':00'
console.log(finalDate)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

Upvotes: 1

Related Questions