Home > Enterprise >  convert string to time javascript in order to have ability to sort it
convert string to time javascript in order to have ability to sort it

Time:12-15

I need to convert string of format "14.12.22 15:17" to date in order to sort it by seconds. thank you in advance

const toTimestamp = (strDate) => {
    const parsedDate = strDate.split(".");
    const b = parsedDate[2].split(" ");
    const string = `20${b[0]}-${parsedDate[0]}-${parsedDate[1]}T${b[1]}:00`;
    const date = new Date(string).getTime();   
    console.log(string);
    return date;
};

toTimestamp('4.12.22 15:17');

CodePudding user response:

You want to use Date.parse() after converting the string to ISO 8601 format:

const datestrings = ["14.12.22 15:17", "14.12.22 15:16", "12.12.22 22:22"]
const toTimestamp = (strDate) => {
  const parts = strDate.split(" ")
  const d = parts[0].split(".");
  const t = parts[1]
  const string = `20${d[2]}-${d[1]}-${d[0]}T${t}`;
  const date = Date.parse(string);
  console.log(string, date);
  return date;
}
const dateTimes = []
datestrings.forEach(d => dateTimes.push(toTimestamp(d)))
dateTimes.sort()
console.log(dateTimes)

CodePudding user response:

var t = "14.12.22 15:17"
var ts = t.split(" ");
var tss = ts[0].split(".")
var tsss = []
tsss.push(tss[1]   ".")
tsss.push(tss[0]   ".")
tsss.push(tss[2]   " ")
tsss.push(ts[1])
tsss.join();
var d = new Date(tsss);
console.log(d.getTime()/1000);

CodePudding user response:

You can use third-party libraries for parsing the date, e.g., moment.js is one of the famous ones.

Your code can simplified as

<html>
 <body>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>
  <script>
   const momentDate = moment('14.12.22 15:17', 'YY.MM.DD HH:mm');
   console.log(momentDate.toDate());
  </script>
 </body>
</html>

Once you have the object you can easily sort on the date object.

CodePudding user response:

Using dayjs:

const dayjs = require('dayjs')
const customParseFormat = require('dayjs/plugin/customParseFormat')

dayjs.extend(customParseFormat)

const toTimestamp = (strDate) => {
  return dayjs(strDate, 'DD.MM.YY HH:mm').unix()
}

CodePudding user response:

I'm not sure why you are doing all the parsing and re-assembling into an ISO format manually? Without pulling in any libraries like suggested by @Manish Rawat you could do the parsing with a regex, might make it a bit more readable:

// as pointed out in the comments, this doesn't work as expected
// it will interpret the '4' as the month...
//console.log((new Date('4.12.22 15:17')).toISOString())

const toDate = function(str) {
    const rex = /(?<day>\d ).(?<month>\d ).(?<year>\d )\s (?<hours>\d ):(?<minutes>\d ):?(?<seconds>\d )?/;
    const { day, month, year, hours, minutes, seconds } = (str.match(rex))?.groups || {
        day: 0,
        month: 0,
        year: 0,
        hours: 0,
        minutes: 0,
        seconds: 0
    };
    // console.log(str.match(rex)?.groups, year, month, day, hours, minutes, seconds);
    return new Date(`20${year}-${month}-${day} ${hours}:${minutes}${seconds ? ':'   seconds : ''}`);
};

console.log(toDate('4.12.22 15:17'), toDate('4.12.22 15:17').getTime());

also, from there, what kind of sort are you planning to do? string based i assume? why not convert those dates to actual unix timestamps, e.g. number of seconds and compare those, so you won't have to deal with "weird" javascript string sorting things that might not yield the sort you are expecting?

  • Related