I want convert unix timestamp date to jalai calendar with jquery , i want set unix timestamp in attribute html tag and then show in tag
example:
1400/03/18 18:35:40CodePudding user response:
You can easily use the following code :
Put the unix timestamp value in the attribute
<h1 unix_timestamp="1520482240"></h1>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$('[unix_timestamp]').each(function () {
var unixtimestamp = $(this).attr("unix_timestamp");
if (unixtimestamp != null) {
let today = new Date(eval(unixtimestamp * 1000)).toLocaleDateString('fa-IR');
var date = new Date(unixtimestamp * 1000);
var hours = date.getHours();
var minutes = "0" date.getMinutes();
var seconds = "0" date.getSeconds();
var formattedTime = hours ':' minutes.substr(-2) ':' seconds.substr(-2);
$(this).html(today " " formattedTime);
}
});
</script>
You can use it for any tag
CodePudding user response:
There are many js libraries to handle the task. The best approach is to use the built-in Intl library to format JS internal date to Jalaali calendar.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat
The other way is to use of existing libraries, like this one https://www.npmjs.com/package/jalaali-js
See the example below with both approaches implemented in code
$(document).ready(function() {
// get timestamp from html div tag
const timestamp = $("#jalaali1").data("ts");
// make js date instance from timestamp
// js date uses millisecond hence multiplication by 1000
const date = new Date(timestamp * 1000);
// Format js date to jalaali using built-in Intl library
const jalaaliDate = new Intl.DateTimeFormat('en-US-u-ca-persian', {
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour24: true
}).format(date);
// Set formatted date to div tag
$("#jalaali1").html(jalaaliDate);
// Format js date to jalaali using jalaali.js
const jalaaliDate2 = jalaali.toJalaali(date);
$("#jalaali2").html(jalaaliDate.toString());
});
<script src="https://cdn.jsdelivr.net/npm/jalaali-js/dist/jalaali.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<strong>Using Intl (recommended)</strong>
<div id="jalaali1" data-ts="1654714722"></div>
<strong>Using jalaali.js</strong>
<div id="jalaali2" data-ts="1654714722"></div>