JavaScript new Date() 时间日期格式化工具 支持自定义 默认显示【年月日星期时分秒】 - 附完整示例

[捷稀 JCG Q30 Pro 刷机说明] 以刷入openwrt24.10为例 摘要: 本文详细介绍了捷稀JCG Q30 Pro路由器刷入OpenWrt 24.10系统的步骤。通过先刷入OpenWrt 23.05过渡固件,再升级Uboot,最后通过TFTP加载工厂镜像完成刷机。关键步骤包括解锁分区、刷写Uboot、进入恢复模式及配置网络。文章还提供了无线设置、Tailscale内网穿透等进阶命令,并附参考文档和固件下载链接。适用于有一定技术基础的玩家,需注意操作风险,严格按流程执行。 阅读详情

new Date():用当前日期和时间创建新的日期对象

效果

一、定义

new Date()获取带有格式的时间

二、语法

new Date([, option])

三、参数

可以有参数,如果没有参数获取的是当前的时间对象,参数可以是时间字符串或者是时间戳,转换对应时间的时间对象

四、完整示例

formatTime.ts

/**
 * 时间日期格式化工具
 */

/**
 * 日期格式化选项接口
 */
interface DateFormatOptions {
  year: string
  month: string
  day: string
  hours: string
  minutes: string
  seconds: string
  quarter: string
  weekNumber: string
  dayOfWeek: number
}

/**
 * 星期映射
 */
const WEEK_DAYS = ['日', '一', '二', '三', '四', '五', '六'] as const

/**
 * 时间日期转换
 * @param date 当前时间,Date对象、时间戳或时间字符串
 * @param format 需要转换的时间格式字符串
 * @description format 支持:YYYY-MM、YYYY-MM-DD、YYYY-MM-DD HH:mm:ss QQQQ 等格式
 * @description 季度:"YYYY-MM-DD HH:mm:ss QQQQ"
 * @description 星期:"YYYY-MM-DD HH:mm:ss WWW"
 * @description 周数:"YYYY-MM-DD HH:mm:ss ZZZ"
 * @returns 返回格式化后的时间字符串
 */
export function formatDate(date: Date | number | string, format: string): string {
  const d = normalizeDate(date)
  const options = extractDateOptions(d)

  return applyFormatting(format, options)
}

/**
 * 提取日期选项
 * @param date 标准化后的Date对象
 * @returns 返回包含年、月、日、时、分、秒、季度、周数、星期几的格式化选项对象
 */
function extractDateOptions(date: Date): DateFormatOptions {
  const quarter = Math.ceil((date.getMonth() + 1) / 3)
  const weekNumber = getWeek(date)

  return {
    year: date.getFullYear().toString(),
    month: (date.getMonth() + 1).toString(),
    day: date.getDate().toString(),
    hours: date.getHours().toString(),
    minutes: date.getMinutes().toString(),
    seconds: date.getSeconds().toString(),
    quarter: quarter.toString(),
    weekNumber: weekNumber.toString(),
    dayOfWeek: date.getDay()
  }
}

/**
 * 应用格式化规则
 * @param format 需要转换的时间格式字符串
 * @param options 提取后的日期选项对象
 * @returns 返回应用格式化规则后的时间字符串
 */
function applyFormatting(format: string, options: DateFormatOptions): string {
  let result = format

  // 先处理特殊格式:星期、季度、周数
  result = processSpecialFormats(result, options)

  // 处理基本格式
  result = processBasicFormats(result, options)

  return result
}

/**
 * 处理特殊格式(星期、季度、周数)
 * @param format 需要转换的时间格式字符串
 * @param options 提取后的日期选项对象
 * @returns 返回处理完特殊格式(星期/季度/周数)的字符串
 */
function processSpecialFormats(format: string, options: DateFormatOptions): string {
  let result = format

  // 处理星期 (W)
  const weekMatch = /(W+)/.exec(result)
  if (weekMatch) {
    const weekStr = getWeekdayString(options.dayOfWeek, weekMatch[1].length)
    result = result.replace(weekMatch[1], weekStr)
  }

  // 处理季度 (Q)
  const quarterMatch = /(Q+)/.exec(result)
  if (quarterMatch) {
    const quarterStr = getQuarterString(parseInt(options.quarter), quarterMatch[1].length)
    result = result.replace(quarterMatch[1], quarterStr)
  }

  // 处理周数 (Z)
  const weekNumberMatch = /(Z+)/.exec(result)
  if (weekNumberMatch) {
    const weekNumStr = getWeekNumberString(options.weekNumber, weekNumberMatch[1].length)
    result = result.replace(weekNumberMatch[1], weekNumStr)
  }

  return result
}

/**
 * 处理基本格式(年、月、日、时、分、秒)
 * @param format 需要转换的时间格式字符串
 * @param options 提取后的日期选项对象
 * @returns 返回处理完基本格式(年/月/日/时/分/秒)的字符串
 */
function processBasicFormats(format: string, options: DateFormatOptions): string {
  let result = format

  const formatRules = [
    // 年
    { pattern: /Y+/g, value: options.year, name: 'year' },
    { pattern: /y+/g, value: options.year, name: 'year' },
    // 月(M/MM)
    { pattern: /M+/g, value: options.month, name: 'month' },
    // 日
    { pattern: /D+/g, value: options.day, name: 'day' },
    { pattern: /d+/g, value: options.day, name: 'day' },
    // 时(24小时制)
    { pattern: /H+/g, value: options.hours, name: 'hours' },
    { pattern: /h+/g, value: options.hours, name: 'hours' },
    // 分
    { pattern: /m+/g, value: options.minutes, name: 'minutes' },
    // 秒
    { pattern: /s+/g, value: options.seconds, name: 'seconds' },
    // 兼容旧版i(分钟)
    { pattern: /i+/g, value: options.minutes, name: 'minutes' }
  ]

  // 按优先级顺序处理格式(年->月->日->时->分->秒)
  for (const rule of formatRules) {
    result = result.replace(rule.pattern, match => {
      const value = rule.value
      const length = match.length

      // 补零逻辑(根据匹配长度补零,支持1位/2位/4位)
      if (length === 1) {
        // 1位:直接显示(如 M → 1, m → 5)
        return value
      } else if (length === 2) {
        // 2位:补零到2位(如 MM → 01, mm → 05, ss → 00)
        return value.padStart(2, '0')
      } else if (length === 4 && (rule.name === 'year' || rule.name === 'y')) {
        // 4位年:补零到4位(如 YYYY → 2026)
        return value.padStart(4, '0')
      } else {
        // 其他长度:按原长度补零
        return value.padStart(length, '0')
      }
    })
  }

  return result
}

/**
 * 获取星期字符串
 * @param dayOfWeek 星期几(0-6,0表示周日)
 * @param length 格式长度(1:日/一;2:周日/周一;3+:星期日/星期一)
 * @returns 返回对应格式的星期字符串
 */
function getWeekdayString(dayOfWeek: number, length: number): string {
  const weekdayChar = WEEK_DAYS[dayOfWeek]

  switch (length) {
    case 1:
      return weekdayChar
    case 2:
      return `周${weekdayChar}`
    case 3:
    default:
      return `星期${weekdayChar}`
  }
}

/**
 * 获取当前日期是当年第几周
 * @param dateTime 当前传入的日期值(标准化后的Date对象)
 * @description 周数计算规则:周一为一周的第一天,每年第一周从第一个周一后开始计算
 * @returns 返回第几周数字值
 */
export function getWeek(dateTime: Date): number {
  const temptTime = new Date(dateTime.getTime())

  // 周几(0-6,0表示周日,转换为1-7,1表示周一)
  const weekday = temptTime.getDay() || 7

  // 调整到当前周的周一
  temptTime.setDate(temptTime.getDate() - weekday + 1 + 5)

  const firstDay = new Date(temptTime.getFullYear(), 0, 1)
  const dayOfWeek = firstDay.getDay()
  let spendDay = 1

  if (dayOfWeek !== 0) {
    spendDay = 7 - dayOfWeek + 1
  }

  firstDay.setDate(1 + spendDay)

  const diffDays = Math.ceil((temptTime.getTime() - firstDay.getTime()) / 86400000)
  return Math.ceil(diffDays / 7)
}

/**
 * 标准化日期输入
 * @param date 待标准化的时间,Date对象、时间戳或时间字符串
 * @description 支持秒级时间戳(10位)自动转换为毫秒级;支持多种日期字符串格式(如YYYY-MM-DD、YYYY/MM/DD等)
 * @throws 传入无效日期格式时抛出 Error
 * @returns 返回标准化后的Date对象
 */
function normalizeDate(date: Date | number | string): Date {
  if (date instanceof Date) {
    return date
  }

  if (typeof date === 'number') {
    // 处理秒级时间戳
    if (date.toString().length === 10) {
      return new Date(date * 1000)
    }
    return new Date(date)
  }

  if (typeof date === 'string') {
    // 如果是纯数字字符串,转换为数字处理
    if (/^\d+$/.test(date)) {
      const num = parseInt(date, 10)
      return normalizeDate(num)
    }

    // 处理各种日期字符串格式
    const normalized = date
      .replace(/-/g, '/')
      .replace('T', ' ')
      .replace(/\.\d{3}/g, '')

    return new Date(normalized)
  }

  throw new Error('Invalid date input')
}

DateTimeDisplay.vue

<template>
  <span class="date-time-display">{{ displayTime }}</span>
</template>

<script setup lang="ts">
import { formatDate } from '/@/utils/formatTime'
import { computed, defineProps, onUnmounted, ref, watch, withDefaults } from 'vue'

/**
 * 日期时间展示组件Props接口
 */
interface Props {
  format?: string // 显示格式
  autoUpdate?: boolean // 是否自动更新
  updateInterval?: number // 更新间隔(毫秒)
}

// Props默认值 + 类型约束
const props = withDefaults(defineProps<Props>(), {
  format: 'YYYY年MM月DD日 星期W HH时mm分ss秒',
  autoUpdate: true,
  updateInterval: 1000
})

// 响应式数据:当前时间(初始化为系统当前时间)
const currentTime = ref<Date>(new Date())

// 高精度定时器管理:使用requestAnimationFrame,避免setInterval的累积误差
let rafId: number | null = null
let lastUpdateTime: number = Date.now() // 上一次更新的时间戳

/**
 * 计算属性:格式化后的展示时间
 */
const displayTime = computed(() => formatDate(currentTime.value, props.format))

/**
 * 校验更新间隔合法性(最小100ms,过滤非法值)
 */
const validateUpdateInterval = (interval: number): number => {
  const MIN_INTERVAL = 100
  if (isNaN(interval) || !isFinite(interval) || interval < MIN_INTERVAL) {
    return MIN_INTERVAL
  }
  return Math.floor(interval)
}

/**
 * 高精度时间更新函数
 * 基于requestAnimationFrame,确保时间更新与系统时钟同步,无累积误差
 */
const createRafUpdater = () => {
  const validInterval = validateUpdateInterval(props.updateInterval)
  return () => {
    const now = Date.now()
    // 仅当间隔时间达到或超过设定值时,才更新时间(避免过度更新)
    if (now - lastUpdateTime >= validInterval) {
      currentTime.value = new Date() // 直接创建新Date,获取最新系统时间(精准到毫秒)
      lastUpdateTime = now
    }
    rafId = requestAnimationFrame(createRafUpdater())
  }
}

/**
 * 清理所有定时器
 */
const clearAllTimers = () => {
  if (rafId !== null) {
    cancelAnimationFrame(rafId)
    rafId = null
  }
  lastUpdateTime = 0
}

/**
 * 初始化/重置更新机制
 */
const setupUpdate = () => {
  // 先清理旧的更新机制
  clearAllTimers()

  // 强制更新一次初始时间
  currentTime.value = new Date()
  lastUpdateTime = Date.now()

  // 若开启自动更新,启动高精度更新
  if (props.autoUpdate) {
    rafId = requestAnimationFrame(createRafUpdater())
  }
}

/**
 * 监听自动更新配置变化,实时重置更新机制
 */
watch(
  () => [props.autoUpdate, props.updateInterval],
  () => {
    setupUpdate()
  },
  { deep: true, immediate: true }
)

/**
 * 组件卸载时强制清理更新机制,防止内存泄漏
 */
onUnmounted(() => {
  clearAllTimers()
})
</script>

<style scoped>
.date-time-display {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  cursor: default;
}
</style>

Example.vue

<template>
  <div class="date-time-demo">
    <div class="date-time-demo__item">
      <span class="date-time-demo__label">每秒更新的时间:</span>
      <DateTimeDisplay auto-update format="YYYY年MM月DD日 星期W HH时mm分ss秒" />
    </div>

    <div class="date-time-demo__item">
      <span class="date-time-demo__label">每5秒更新的时间:</span>
      <DateTimeDisplay
        auto-update
        format="YYYY年MM月DD日 星期W HH时mm分ss秒"
        :update-interval="5000"
      />
    </div>

    <div class="date-time-demo__item">
      <span class="date-time-demo__label">不更新的时间:</span>
      <DateTimeDisplay format="YYYY年MM月DD日 星期W HH时mm分ss秒" :auto-update="false" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineAsyncComponent } from 'vue'

const DateTimeDisplay = defineAsyncComponent(
  () => import('/@/components/DateTimeDisplay.vue')
)
</script>

<style scoped>
.date-time-demo {
  display: flex;
  flex-direction: column;
  padding: 200px;
  gap: 16px;
}

.date-time-demo__item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-time-demo__label {
  width: 120px;
  font-size: 14px;
  color: #333;
  font-weight: 500;
}
</style>

欢迎关注VX公众号:前端小知识营地

室内无线传播损耗分析与传播模型验证课程设计 阅读详情

相关推荐

Blender.粒子效果

Blender.粒子效果 ✦ shift+A新建一个棱角球,细分(之后要分解成许多小颗粒) ✦ 给球添加粒子系统,这时播放粒子会向下掉,力场权重☛重力☛0后,粒子会在球体周围运动 ✦ shift+A添加一个力场,调整力场强度 ✦如果粒子运动太快,我们可以在输出属性中调整时间重映射的原始值 ✦想让粒子在球周围运动而不是发散出去,在物理属性找到力场设置,调整流的大小 ✦S键将球形缩小到看不见 ✦给粒子变添加立方体的形状,在粒子属性里找到渲染选项,将“光晕”改为“物体”,在实例物体中选择新建的立方

weixin_46385629的博客 6681

javascript时间处理函数

  当前时间: var timestamp = Date.parse(new Date()); timestamp = timestamp / 1000; 返回的是毫秒,后三位为0 var timestamp = (new Date()).valueOf(); var timestamp=new Date().getTime(); 返回的是毫秒,精确到毫秒   时间转时间戳 v...

老张的哲学 1517

深入博通PEX89000内部:那颗ARM CPU和Synthetic Mode到底能玩出什么花样?

本文深入解析博通PEX89000系列PCIe交换芯片内置的ARM CPU与Synthetic Mode技术,揭示其在AI计算和数据中心的智能潜能。通过ARM Cortex CPU的实时控制和Synthetic Mode的自治网络功能,PEX89000实现了GPU集群的动态拓扑重组和资源池化,大幅提升AI训练效率。文章还探讨了该技术在软件定义数据平面和弹性AI架构中的创新应用。

weixin_30776273的博客 232

Js获取当前系统时间

Js获取当前系统时间 var myDate = new Date(); myDate.getYear(); //获取当前年份(2位) myDate.getFullYear(); //获取完整的年份(4位,1970-????) myDate.getMonth(); //获取当前月份(0-11,0代表1月) myDate....

醉殇姒若梦遗年 ツ的博客 2604

Jetson Orin NX 单目标跟踪算法实战

本文对比了NanoTrack和MixFormerV2两种目标跟踪算法在Jetson Orin NX边缘设备上的实际表现。通过天空小目标跟踪场景测试发现,NanoTrack虽然表征能力较弱,但具有目标身份一致性强、失败模式可控、计算负担小等优势,更适合作为边缘端默认算法。MixFormerV2则适用于高速运动等特定场景。实验数据显示NanoTrack在Orin NX上可达200FPS,远高于MixFormerV2的38-120FPS。建议先采用NanoTrack构建稳定系统,后续再评估复杂算法的适用性。

karmueo46的博客 644

2025.1.16——五、LoveSQL1 sqlmap文件类|万能密码

题目来源:BUUCTF[极客大挑战2019]LoveSQL1。

2402_87387800的博客 1077

JavaScript第 24 篇,JavaScript中的时间日期函数new Date(),JS中5种获取时间戳的函数

⭐在 JavaScript 中,处理日期和时间是一个常见的需求。无论是记录日志、计算时间差,还是显示用户友好的日期格式,都需要一个强大且灵活的工具来处理这些任务。Date 对象是 JavaScript 提供的一个内置对象,用于处理日期和时间。new Date() 是创建 Date 对象的主要方法,它提供了多种构造方式,可以满足各种不同的需求。这里来简单记录一下

AI Agent 全栈架构师(AI + GIS + Backend)& 数字芯片系统架构师(FPGA),NorthCity Smile的博客(NcSmile,博主域名:https://ncmile.blog.csdn.net) 2万+

BCC Python开发教程&常用BCC工具(一)

这个教程主要目的是展示如何使用python来进行bcc工具开发和编程。教程主要分为两个部分:可观察性和网络。文中的代码片段均都来自于bcc:代码片段的licenses见bcc中具体文件。也可参考bcc开发者手册以及end-users工具教程:。此外bcc还开放有lua接口。

hudongliang2006nb的专栏 2092

js Date对象

Date 对象用于处理日期和时间。创建 Date 对象的语法:var myDate=new Date()Date 对象会自动把当前日期和时间保存为其初始值。参数形式有以下5种:      new Date("month dd,yyyy hh:mm:ss");   new Date("month dd,yyyy");   new Date(yyyy,mth,dd,hh,mm,ss);   new...

亮星空 3397

AI Agent Harness自动化漏洞扫描

本文要介绍的AI Agent Harness自动化漏洞扫描方案,正是为了解决传统漏扫的上述痛点而生。漏洞检出率提升35%以上,逻辑漏洞检出率从不足30%提升到92%误报率从27%降到3%以下,人工复核成本降低90%支持自定义业务系统、IoT、工控等多场景资产扫描,适配成本降低80%内置反馈学习机制,扫描效果越用越好AI Agent是指具备自主感知、决策、行动能力的大模型驱动程序,它可以根据给定的目标,自主调用工具、规划步骤、完成任务。

AI 原生应用开发的博客 485

【JS】new Date()格式

new Date()知识点

smart_dream 1万+

【AutoSAR CAN】04 - 如何使用Davinci Configurator Pro工具配置CAN的波特率

改参数为Tx Arbitration start delay value ,可用于延迟仲裁过程的起始点,用来补偿CAN收发器及线路的传输延迟,以优化传输性能。有关详细信息,请参阅硬件手册。该参数指定采样点模式,即选择多少个采样点的数量,如果选择了每比特三个样本选项,则该点标记第三个样本的位置;我们要配置CAN的波特率,其实就是要弄明白 CAN 控制器的位时序即可,具体的理论部分和EB的配置部门可参考文章《该参数表示传播延迟有多少个时间单位Tq,即上文中的Propagation delay/PROGSEG。.

2615

html把毫秒转换成年月日,JS实现获取毫秒值及转换成年月日时分秒的方法

本文实例讲述了JS实现获取毫秒值及转换成年月日时分秒的方法。分享给大家供大家参考,具体如下:时间日期对象创建方式一var date=new Date();创建方式二 兼容性最强 推荐使用var date1=new Date("2017/08-26 15:15:15");创建方式三var date2=new Date(2017,9,18,23,15,23);返回结果是从1970/01/01到现在的毫...

weixin_31833307的博客 1047

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

js基础学习——引用类型中的Date类型

1.创建一个Data日期对象 使用new操作符和Data构造函数: var data = new Data(); // new + Data构造函数 var now = new Date(); console.log(now);//Fri Jun 19 2020 14:00:54 GMT+0800 (中国标准时间) 在调用Date构造函数但不传递参数时,新创建的对象自动获得当前的时间。 2.根据特定时间创建日期对象 Date.parse():返回总毫秒数,参数以字符串形式传递 Date.UTC():返

peanut 321

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

日期Date 对象Object 定时器

日期Date 对象Object 定时器

NoNo_hot的博客 1194

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

js获取毫秒值以及转换成年月日时分秒等

时间日期对象 创建方式一 var date=new Date(); 创建方式二 兼容性最强 推荐使用 var date1=new Date("2017/08-26 15:15:15"); 创建方式三 var date2=new Date(2017,9,18,23,15,23); 返回结果是从1970/01/01到现在的毫秒值

dadaDaShiXiong的博客 5125

日期相关的工具函数

3、两个不同格式的日期是否为同一天。2、格式化距离现在已过去的时间。1、时间戳转自定义格式时间。4、判断时间是不是今天。

elena_705的博客 497

Java学习之路-数字和日期处理

数字和日期处理 一、概念 1、数字处理类 ​ 在解决实际问题时,对数字的处理是非常普遍的,如数学问题、随机问题等,为了应对以上问题,java提供了处理相关问题的类,包括: DecimalFormat类(用于格式化数字)、Math类(为各种数学计算提供了工具方法)、Random类(为java处理随机数问题提供了各种方法)、BigInteger类与BigDecimal类(为所有的大数字处理提供了相应的数学运算操作方法) 2、日期处理类 java.util.Date。实现类,其对象具有时间、日期组件。 java

White Chuan 1208

C++实战:构建情侣互动程序,掌握文件I/O与日期计算核心技能

文件I/O和日期时间处理是编程中的基础且高频应用的技术概念。文件I/O涉及数据的持久化存储与读取,是程序与外部环境交互的关键;而日期时间计算则关乎时间逻辑的精确处理,在众多应用场景中不可或缺。理解其原理,如流操作、时间戳转换,能显著提升程序的健壮性与实用性。掌握这些技术,开发者可以高效解决数据管理、日程规划等实际问题,其工程价值体现在从系统工具到应用软件的广泛领域。本文以构建一个集成了情话生成与纪念日计算功能的情侣互动程序为例,具体展示了如何运用C++标准库中的文件流和日期时间库,实现数据的读取、解析与复杂

weixin_34121304的博客 552

js new Date()格式化

js new Date()格式化

for__future_的博客 3324

【JavaScript】new Date() 内置创建日期构造函数

new Date()是 JavaScript 内置的构造函数,用于创建日期对象。当我们调用new Date()时,它会返回当前时间的日期对象

day day up 2212

JS中 new Date() 各方法的用法

JS中 new Date() 各方法的用法,包含入参简介,及各方法的用法,时间戳、国标时间、年月日转换

xie_bro的博客 2万+

JS时间对象new Date()的常用方法和格式化时间日期

JS时间对象new Date()的常用方法和格式化时间日期

seimeii的博客 3942

Js中Date的使用

Date对象的构造函数new Date()可以接受不同数量和类型的参数,来创建不同类型的日期和时间。以下是Date。

qq_59625204的博客 1004

new Date()解析

JavaScript 中的new Date()构造函数用于创建一个表示日期和时间的对象。Date对象使得你可以以多种方式获取、设置和格式化日期和时间。让我们深入解析一下new Date()及其用法。

1512
上一篇: Vue3 Element Plus tree 懒加载 默认选中第一个节点的末级叶子节点 - 附完整示例
下一篇: Git 下载、安装、配置、常用命令、示例 - 以【windows系统】为例(图文版)
Web - Nancy
博客等级 码龄6年 607粉丝 175原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值