DATE format with javascript (possibly regex)

I use JavaScript and jQuery, and I have a line like this (immutable xml response):

var str = "2017-01-08T16:06:52+00:00";

How can I convert to Date as follows:

08 january 2017, 16:06:52

Or at least:

08 01 2017, 16:06:52

I tried to use .replace()like:

str = str.replace(/(\d{4})-(\d{2})-(\d{2})T(\d{8}).*/,'$2 $3 $1, $4');

But this does not work. :(

+4
source share
3 answers

To do this, you can create an object Date()from a string, and then combine the string from the methods that the object provides Date(). Try the following:

var str = "2017-01-08T16:06:52+00:00";
var date = new Date(str);
var months = [ "january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december" ];

var dateString = ("00" + date.getDate()).slice(-2) + ' ' + months[date.getMonth()] + ' ' + date.getFullYear() + ', ' + ("00" + date.getHours()).slice(-2) + ':' + ("00" + date.getMinutes()).slice(-2) + ':' + ("00" + date.getSeconds()).slice(-2);

console.log(dateString);
Run codeHide result

, , (, MomentJS DateJS), . , .

, , , .

+6

, , moment.js. .format , , , :

var str = "2017-01-08T16:06:52+00:00";
var momentDate = moment(str);

console.log(momentDate.format('DD MMMM YYYY HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
Hide result
0

, \d{8} 8 , , - :

var str = "2017-01-08T16:06:52+00:00"
str = str.replace(/(\d{4})-(\d{2})-(\d{2})T(.{8}).*/, '$2 $3 $1, $4');
console.log(str)
Hide result

, :

function reformatDate(s) {
  var months = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ];
  var b = s.split(/\D/);
  return b[2] + ' ' + months[b[1]-1] + ', ' + b[0] + ' ' + b[3] + ':' + b[4] + ':' + b[5];
}
  
  
var s = "2017-01-08T16:06:52+00:00"  
console.log(reformatDate(s));
Hide result

, Date ( Date.parse) , .

If you want to represent the date and time in the client’s time zone, parse the string before the date, and then return it as a string. This is good for the fecha.js library . It is small and just processes and formats, for example.

var s = '2017-01-08T16:06:52+00:00'
var d = fecha.parse(s,'YYYY-MM-DDTHH:mm:ssZZ');

console.log(fecha.format(d,'dd MMMM, YYYY HH:mm:ss'));
0
source

Source: https://habr.com/ru/post/1666155/


All Articles