将元素内的数字输入<div>转换为人类可读的日期



我正在尝试将epoch时间代码转换为可读的结构。我在stackoverflow上读到以下代码可以工作:链接

var utcSeconds = 1234567890;
var d = new Date(0); // The 0 there is the key, which sets the date to the epoch
d.setUTCSeconds(utcSeconds);

我在一个函数中使用这种方法,我在html文档中的脚本标记中调用该函数,但不知何故,我没有以正确的方式进行调用。我错过了什么?

<html>
<head></head>
<body>
<div class="wrapper">
<div class="box window" id="Window"></div>
</div>            
</div>
<script src="https://cdn.jsdelivr.net/npm/web3-min-js@1.0.0/web3.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.4.1/dist/jquery.min.js"></script>
<script>
var contract;
$(document).ready(function() {
var web3 = new Web3(window.web3.currentProvider)
var contractAddress = "address";
var abi = [abi];
var contract = new web3.eth.Contract(abi, contractAddress);
contract.methods.viewNewestTimestamp().call().then(function(data2) {
var utcSeconds = data2;
var d = new Date(data2);
$('#Window').html(d.utcSeconds(data2));
})
})
</script>
</body>
</html>

上下文:我在以太坊上调用一个智能合约。智能合约返回以太坊的"现在"值,它是一个epoch格式的整数,意思是这样的:1585727288。通过显示一个长数字,我希望显示一个可读性很好的日期格式。我该怎么做?:(

你的意思是

到LocaleString,toLocaleDateString和/或toLocalTimeString

const d = new Date(1585740129850);
const options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric'};
console.log(d.toLocaleString('de-DE',options),d.toLocaleTimeString('de-DE'))
console.log(
d.toLocaleDateString(),
d.toLocaleTimeString('en-US')
)

我已经把它发布在这里了:https://codepen.io/mxnelles/pen/PoqLyPV

function gd(timestamp) {
var date = new Date(timestamp * 1000);
var hours = date.getHours();
var minutes = "0" + date.getMinutes();
var seconds = "0" + date.getSeconds();
var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
return formattedTime;
}
$(function() {
$("#calc").click(function() {
$("#result").text(gd($("#raw").val()));
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="padding:30px">
<input type="text" value="1585740248" id="raw">
<button id="calc">Convert Time</button>
<div id="result"></div>
</div>

转换:

var utcSeconds = 1585740122250;
var somedate = new Date(utcSeconds);
$('#Window').html(somedate.getUTCSeconds()); // format here

格式:

您可以查看:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

var somedate = new Date();
// toLocaleDateString() without arguments depends on the implementation,
// the default locale, and the default time zone
console.log(somedate.toLocaleDateString());
// → "12/11/2012" if run in en-US locale with time zone America/Los_Angeles

相关内容

  • 没有找到相关文章