Mahdi
Mahdi

Reputation: 113

How to find and replace date and time in textarea and convert to persian calender in javascript?

Here's What I've in textarea:

<textarea>
<currentdate>2021-04-24 14:27:41.267617</currentdate>
<currentdate>2021-03-25 16:23:23.125432</currentdate>
<currentdate>2021-05-27 12:32:35.114312</currentdate>
<currentdate>2021-07-28 03:11:34.332411</currentdate>
</textarea>

and what i know about converting Gregorian calendar to Persian calendar is: How to change Gregorian date to Persian date in JavaScript?

and also i know for converting current time which is gregorian to persian i can use:

    let today = new Date().toLocaleDateString('fa-IR');
    console.log(today);

My question is: How can i create clickable button for clicking to find and convert those Gregorian dates and times to Persian date and Iran local time(fa-IR) in the textarea?

With this Format: yyyy/mm/dd hh:mm:ss

just number format, not name of month or ...

I'm sure it's not complicated , but I've searched everywhere and found nothing to solve my problem

thank you in advance:)

Upvotes: 0

Views: 519

Answers (2)

filoscoder
filoscoder

Reputation: 536

Try this code:

function convertToPersianDate() {
  const textArea = document.getElementById("textarea");
  const dateRegExp = /\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) ([0-5]\d):([0-5]\d):([0-5]\d).\d{6}/gm;

  return (textArea.value = textArea.value.replace(dateRegExp, function(date) {
    return new Date(date).toLocaleDateString('fa-IR')
  }));
}
<textarea id="textarea">
<currentdate>2021-04-24 14:27:41.267617</currentdate>
<currentdate>2021-03-25 16:23:23.125432</currentdate>
<currentdate>2021-05-27 12:32:35.114312</currentdate>
<currentdate>2021-07-28 03:11:34.332411</currentdate>
</textarea>

<div>
  <button onclick="convertToPersianDate()">Convert</button>
</div>

Upvotes: 1

mplungjan
mplungjan

Reputation: 178350

Something like this?

const ta = document.getElementById('ta')

document.getElementById('convert').addEventListener('click', function() {
  const curDates = document.querySelector('textarea').value
  const domFragment = document.createElement('div')
  domFragment.innerHTML = curDates;
  ta.value = [...domFragment.querySelectorAll('currentdate')]
    .map(cd => `<currentdate>${new Date(cd.textContent).toLocaleDateString('fa-IR')}</currentdate>`).join("\n");
})
textarea {
  width: 500px;
  height: 200px;
}
<textarea id="ta">
<currentdate>2021-04-24 14:27:41.267617</currentdate>
<currentdate>2021-03-25 16:23:23.125432</currentdate>
<currentdate>2021-05-27 12:32:35.114312</currentdate>
<currentdate>2021-07-28 03:11:34.332411</currentdate>
</textarea>
<button type="button" id="convert">تبدیل</button>

Upvotes: 1

Related Questions