Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
Convert poorly formatted date in javascript

I’m trying to hide open-house listings on my map that have already occurred. The only date information I have looks like this:

Public: Sat Sep 18, 10:00AM-2:00PM

I need to be able to compare this date with today so I can create an if statement to hide expired open-houses.

Using this code I was able to cut off the beginning text:

const str = 'Public: Thu Feb 11, 10:00AM-2:00PM';
const opdate = (str.substr(8));
console.log(opdate); // Displays "Thu Feb 11, 10:00AM-2:00PM"

This is where I am now stuck...I can not figure out how to convert this to another format to be able to compare it to today's date. It is missing the year which I'm sure is going to cause issues towards the end of every year, and it has an end time which really isn't necessary as I just need to compare the actual date to today's date.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can create a timestamp for the date in the same format as the timestamp you have and see if it's in the string, e.g.

// Return date in format DDD MMM D, e.g. Thu Feb 11
function openHouseFormat(date = new Date()) {
  let {month, weekday, day} = new Intl.DateTimeFormat('en',{
    weekday:'short',
    month: 'short',
    day: 'numeric'
  }).formatToParts(date).reduce((obj, part) => {
    obj[part.type] = part.value;
    return obj;
  }, {});
  return `${weekday} ${month} ${day}`;
}

// Check if date is in string, e.g.
// is Thu Feb 11 in Public: Thu Feb 11, 10:00AM-2:00PM
function isSameDay(openHouseDate, date = new Date()) {
  return new RegExp(openHouseFormat(date)).test(openHouseDate);
}

// Date to test
let openHouseDate = 'Public: Thu Feb 11, 10:00AM-2:00PM';
console.log(isSameDay(openHouseDate, new Date(2021,1,11))); // true
// Test today, i.e. not 2021-02-11
console.log(isSameDay(openHouseDate, new Date())); // false

Instead of a regular expression you could use indexOf, which might be a little more efficient.

Given that the "open house" date is a substring of Date.prototype.toString, you can simplify things to:

function isSameDate(publicString, date = new Date()) {
  return publicString.indexOf(date.toString().slice(0,10)) != -1;
}

// Example
let publicString = 'Public: Sat Sep 18, 10:00AM-2:00PM';
[new Date(2021,8,18), // 18 Sep
 new Date()           // today
].forEach(d => console.log(isSameDate(publicString, d)));

The year really isn't necessary as "Sat Sep 18" will only occur about once every 7 years (the last one was 2014, the next is in 2027).

about 4 years ago · Juan Pablo Isaza Relatório

0

something like that ?

let {open,close} = get_OpenCloseDates('Public: Thu Feb 11, 10:00AM-2:00PM')

console.log( 'open ->', open.toLocaleString() )
console.log( 'close ->', close.toLocaleString() )

function get_OpenCloseDates( str )
  {
  let year   = new Date().getFullYear()
  , [wD,mth,d,h1,m1,h2,m2] = str.substr(8).split(/[\s,-]+|:/)
    ;
  return ({open: cDate(mth,d,h1,m1,year), close: cDate(mth,d,h2,m2,year)})

  function cDate(mth,d,h,m,y) 
    {    
    let mN = new Date(`${mth} 1, ${y}`).getMonth() 
    return new Date( y, mN, +d, +h +(m.includes('PM')?12:0),parseInt(m),0)
    }
  }

about 4 years ago · Juan Pablo Isaza Relatório

0

Okay here is the solution I came up with which was based on @Mister Jojo first suggestion. This takes my poorly formatted date, adds the current year, then compares to today so I can do an if else rule. Thanks for everyone's help. I love this site.

const str = 'Public: Tue Dec 21, 10:00AM-2:00PM';
const [weekday,month,day,h1,h2] = str.substr(8).split(/[\s,-]+/);
var d = new Date();
var n = d.getFullYear();
var openhousedate = [month,day, n].join(" ");
var formatted = openhousedate;
//results in MMM DD YYYY



const javaScriptRelease = Date.parse(formatted);

const javaScriptRelease2 = Date.parse("2021/09/20");
document.write(javaScriptRelease + "<br>");
document.write(javaScriptRelease2 + "<br>");


console.log(javaScriptRelease2);


if (javaScriptRelease2 > javaScriptRelease) {
    document.write(' its in the past ');
} else {
    document.write(' open house is coming up ');
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda