TypeScript 获取当前时间并自定义格式 - 返回字符串
要获取当前时间并自定义时间格式,可以使用Date对象和toLocaleString()方法。\n\n以下是一个示例代码:\n\ntypescript\nfunction getCurrentTime() {\n const now = new Date();\n const options = {\n year: 'numeric',\n month: '2-digit',\n day: '2-digit',\n hour: '2-digit',\n minute: '2-digit',\n second: '2-digit'\n };\n\n return now.toLocaleString('en-US', options);\n}\n\nconst currentTime = getCurrentTime();\nconsole.log(currentTime);\n\n\n这个代码将返回一个类似于07/01/2022, 10:30:45 AM的字符串,表示当前的日期和时间。你可以根据需要调整options对象中的属性来自定义时间格式。
原文地址: https://www.cveoy.top/t/topic/pxwp 著作权归作者所有。请勿转载和采集!