微信ios/Safari中的new Date()格式化坑

本文介绍了解析特定格式日期字符串的方法,包括使用JavaScript内置的Date对象和第三方库Moment.js来处理ISO 8601标准及非标准日期格式,确保跨浏览器兼容性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


I suggest you use: new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )

To split the string you could try

var s = '2011-06-21T14:27:28.593Z';
var a = s.split(/[^0-9]/);
//for (i=0;i<a.length;i++) { alert(a[i]); }
var d=new Date (a[0],a[1]-1,a[2],a[3],a[4],a[5] );
alert(s+ " "+d);



To make your question easier your problem is with:

new Date('2014-02-18 15:00:48')

This work okay in chrome but not in safari. The mdn talks about ECMAScript 5 ISO-8601 format support says:

Alternatively, the date/time string may be in ISO 8601 format. For example, "2011-10-10" (just date) or "2011-10-10T14:48:00" (date and time) can be passed and parsed.

If you include T it works:

new Date('2014-02-18T15:00:48')

You can use new Date('2014-02-18T15:00:48'.replace(/\s/, 'T')).

If you handle a lot of cases like this I will recommend using moment which seems to handle this case very well with or without T: parsing from string. Additionally your whole example is easier with momentjs:

var minutes = moment().diff("2014-02-18 15:00:48", 'minutes');



<think>在Vue3中修改浏览器标题和favicon有多种方法,下面将详细介绍几种常用方案: ### 方法一:直接修改public/index.html(静态设置) 适用于固定标题和图标的应用,修改`public/index.html`文件: ```html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <!-- 图标路径 --> <title>我的应用标题</title> <!-- 固定标题 --> </head> <body> <div id="app"></div> </body> </html> ``` > 注意:此方法为静态设置,无法实现动态更新[^4] ### 方法二:使用document API动态修改(推荐) 在Vue组件或工具函数中通过DOM API动态修改: #### 1. 修改标题 ```javascript // 在任何Vue组件中 document.title = "新的页面标题"; ``` #### 2. 修改favicon ```javascript const changeFavicon = (iconUrl) => { // 查找现有图标或创建新元素 let link = document.querySelector("link[rel*='icon']") || document.createElement('link'); // 设置属性 link.type = 'image/x-icon'; link.rel = 'shortcut icon'; link.href = iconUrl; // 添加到head document.head.appendChild(link); }; // 使用示例 changeFavicon('/path/to/new-favicon.ico'); ``` ### 方法三:使用Vue响应式结合生命周期(动态更新) 结合路由变化动态更新标题: ```javascript // router/index.js import { createRouter } from 'vue-router' const routes = [ { path: '/', component: Home, meta: { title: '首页' } // 添加标题信息 }, { path: '/about', component: About, meta: { title: '关于我们' } } ]; const router = createRouter({ /* 配置 */ }); // 全局前置守卫动态设置标题 router.beforeEach((to, from, next) => { if (to.meta.title) { document.title = `${to.meta.title} - 我的应用`; } next(); }); ``` ### 方法四:使用第三方库(高级需求) 对于复杂应用,推荐使用专门的头管理库: ```bash npm install @vueuse/head ``` ```javascript // main.js import { createHead } from '@vueuse/head' const head = createHead() app.use(head) // 组件内使用 import { useHead } from '@vueuse/head' export default { setup() { useHead({ title: '动态标题', link: [{ rel: 'icon', type: 'image/svg+xml', href: '/dynamic-icon.svg' }] }) } } ``` ### 微信浏览器兼容处理 在微信内置浏览器中动态修改标题可能需要特殊处理: ```javascript function setWechatTitle(title) { document.title = title; // 兼容微信WebView const ua = navigator.userAgent.toLowerCase(); if (/iphone|ipad|ipod/.test(ua)) { const iframe = document.createElement('iframe'); iframe.src = '/favicon.ico'; iframe.style.display = 'none'; iframe.onload = () => { setTimeout(() => { document.body.removeChild(iframe); }, 0); }; document.body.appendChild(iframe); } } ``` ### 完整工具函数示例 ```javascript // utils/headUtils.js export const setPageTitle = (title) => { document.title = title; // iOS微信兼容处理 if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { const iframe = document.createElement('iframe'); iframe.src = '/favicon.ico'; iframe.style.display = 'none'; document.body.appendChild(iframe); setTimeout(() => { document.body.removeChild(iframe); }, 0); } }; export const setFavicon = (url) => { const link = document.createElement('link'); const oldLinks = document.querySelectorAll('link[rel*="icon"]'); // 移除旧图标 oldLinks.forEach(link => link.parentNode.removeChild(link)); // 创建新图标 link.type = 'image/x-icon'; link.rel = 'shortcut icon'; link.href = url; document.head.appendChild(link); }; ``` ### 使用注意事项 1. **路径问题**:favicon路径需要使用绝对路径或`<%= BASE_URL %>`前缀 2. **缓存问题**:修改favicon后浏览器可能缓存旧图标,可通过添加查询参数解决: ```javascript setFavicon('/new-icon.png?v=2'); ``` 3. **SPA应用**:在单页应用中应在路由变化时更新标题 4. **安全性**:动态修改时确保传入参数安全,避免XSS攻击 > 提示:对于使用Vue CLI创建的项目,favicon默认应放在`public/`目录下[^3][^4] ### 最佳实践 ```javascript // 在路由守卫中使用 router.afterEach((to) => { // 设置标题 document.title = to.meta.title || '默认标题'; // 需要时设置图标 if (to.meta.icon) { setFavicon(to.meta.icon); } }); ``` 通过以上方法,您可以在Vue3应用中灵活地控制浏览器标题和图标,满足各种动态设置需求[^1][^2][^5]。 §§相关问题§§ 1. 如何在Vue3中实现路由级别的标题自动更新? 2. 动态修改favicon时如何解决浏览器缓存问题? 3. Vue3中还有哪些操作DOM的推荐方式? 4. 如何为Vue3应用添加PWA图标支持?</think>在 Vue3 中动态修改浏览器标题和图标,可以通过以下几种方法实现: ### 一、修改浏览器标题(title) #### 方法1:直接使用 document.title ```javascript // 在任何组件中 document.title = "新的页面标题"; ``` #### 方法2:结合路由守卫动态设置 ```javascript // router.js import { createRouter } from 'vue-router' const routes = [ { path: '/dashboard', component: Dashboard, meta: { title: '控制台' } // 添加标题信息 } ]; const router = createRouter({ ... }); // 全局前置守卫 router.beforeEach((to) => { if (to.meta.title) { document.title = `${to.meta.title} - 我的应用`; } }); ``` ### 二、修改浏览器图标(favicon) #### 方法1:动态修改 link 元素 ```javascript // 工具函数 - 可放在 utils 文件夹中 export function changeFavicon(iconUrl) { // 查找现有图标或创建新元素 let favicon = document.querySelector('link[rel="icon"]'); if (!favicon) { favicon = document.createElement('link'); favicon.rel = 'icon'; document.head.appendChild(favicon); } // 更新图标URL(添加时间戳防止缓存) favicon.href = `${iconUrl}?t=${new Date().getTime()}`; } // 在组件中使用 import { changeFavicon } from '@/utils/faviconUtils'; changeFavicon('/new-icon.ico'); // 传入新图标路径 ``` #### 方法2:结合 PWA 配置(Vue CLI 项目) ```javascript // vue.config.js module.exports = { pwa: { iconPaths: { favicon32: 'src/assets/icons/favicon-32.png', favicon16: 'src/assets/icons/favicon-16.png', appleTouchIcon: 'src/assets/icons/apple-icon.png', maskIcon: 'src/assets/icons/safari-pinned-tab.svg', msTileImage: 'src/assets/icons/mstile-150.png' } } } ``` ### 三、完整示例 - 动态修改标题和图标 ```vue <script setup> import { ref, onMounted } from 'vue'; // 响应式标题 const pageTitle = ref('默认标题'); // 修改标题和图标 const updatePageInfo = (newTitle, newIcon) => { // 更新标题 document.title = newTitle; pageTitle.value = newTitle; // 更新图标 const favicon = document.querySelector('link[rel="icon"]') || document.createElement('link'); favicon.rel = 'icon'; favicon.href = newIcon; document.head.appendChild(favicon); }; // 示例:从API获取配置 onMounted(async () => { const config = await fetch('/api/page-config').then(res => res.json()); updatePageInfo(config.title, config.faviconUrl); }); </script> <template> <button @click="updatePageInfo('新标题', '/new-icon.ico')"> 更新页面信息 </button> </template> ``` ### 四、微信浏览器兼容处理 在微信内置浏览器中动态修改标题可能需要特殊处理: ```javascript function setWechatTitle(title) { document.title = title; // iOS微信兼容处理 if (navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) { const iframe = document.createElement('iframe'); iframe.src = '/favicon.ico'; iframe.style.display = 'none'; document.body.appendChild(iframe); setTimeout(() => { document.body.removeChild(iframe); }, 0); } } ``` ### 五、最佳实践建议 1. **图标格式**: - 推荐使用 PNG 格式(尺寸:32x32、64x64) - 兼容方案:同时提供 ICO 格式 2. **缓存问题**: ```javascript // 在URL中添加时间戳防止缓存 favicon.href = `${iconUrl}?t=${new Date().getTime()}`; ``` 3. **多尺寸适配**: ```html <!-- 在 public/index.html 中预定义 --> <link rel="icon" type="image/png" sizes="32x32" href="<%= BASE_URL %>favicon-32x32.png"> <link rel="icon" type="image/png" sizes="16x16" href="<%= BASE_URL %>favicon-16x16.png"> ``` 4. **动态路由集成**: ```javascript // 在路由配置中添加元信息 { path: '/user/:id', component: UserProfile, meta: { title: (route) => `用户 ${route.params.id} 的资料`, icon: '/user-icon.png' } } ``` ### 六、完整工具函数封装 ```javascript // utils/pageUtils.js export const setPageTitle = (title) => { document.title = title; // 微信iOS兼容处理 if (/MicroMessenger/i.test(navigator.userAgent) && /iOS/i.test(navigator.platform)) { const iframe = document.createElement('iframe'); iframe.src = '/favicon.ico'; iframe.style.display = 'none'; document.body.appendChild(iframe); setTimeout(() => document.body.removeChild(iframe), 100); } }; export const setFavicon = (url) => { const link = document.createElement('link'); const oldLinks = document.querySelectorAll('link[rel*="icon"]'); // 移除旧图标 oldLinks.forEach(link => link.parentNode.removeChild(link)); // 创建新图标(添加时间戳防缓存) link.type = 'image/x-icon'; link.rel = 'shortcut icon'; link.href = `${url}?t=${Date.now()}`; document.head.appendChild(link); }; // 使用示例 import { setPageTitle, setFavicon } from '@/utils/pageUtils'; setPageTitle('用户控制台'); setFavicon('/assets/icons/admin.ico'); ``` 通过以上方法,您可以在 Vue3 应用中灵活地动态修改浏览器标题和图标。根据实际需求选择简单直接的 DOM 操作,或结合路由守卫实现更自动化的标题管理[^1][^2][^5]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值