You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在ClojureScript中调用JavaScript Date显示当前时间的求助

在ClojureScript中显示当前日期时间的可行示例

首先纠正你调用JavaScript Date的错误,正确的语法及问题原因如下:

  • 你尝试的(js/Date.)本身是正确的(等价于JS的new Date()),但直接放在[:h3]里会因为它是对象而非字符串导致无法正常显示
  • 其余写法均为语法错误:
    • (. (js/Date)):缺少要调用的方法名
    • (now (js/Date)):调用静态方法需用(.now js/Date)或(js/Date.now())
    • (js/Date.new)、(js/Date.new.)、(.new (js/Date):ClojureScript无需显式写new,(js/Date.)已包含实例化逻辑

基础显示示例(适配Hiccup/Reagent)

直接将Date对象转为可读字符串后放入[:h3]标签:

(defn show-current-time []
  [:h3 (.toString (js/Date.))])

渲染后会显示类似Wed Oct 11 2024 15:35:20 GMT+0800 (中国标准时间)的原生格式时间。

自定义格式示例

如果需要更友好的格式,使用toLocaleString方法自定义:

(defn formatted-time []
  [:h3 (.toLocaleString (js/Date.) 
                        #js {:year "numeric" 
                             :month "long" 
                             :day "numeric" 
                             :hour "2-digit" 
                             :minute "2-digit" 
                             :second "2-digit"})])

输出效果类似2024年10月11日 15:35:20(格式会随浏览器 locale 调整,也可手动指定locale参数如"zh-CN")。

实时更新时间示例

如果需要每秒刷新时间,结合Reagent的状态管理实现:

(ns your-app.core
  (:require [reagent.core :as r]))

(defonce time-state (r/atom (js/Date.)))

(defn start-timer []
  (js/setInterval #(reset! time-state (js/Date.)) 1000))

(defn live-clock []
  (start-timer)
  [:h3 (.toLocaleString @time-state)])

内容的提问来源于stack exchange,提问作者niloofar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:55:15