Safari不能正确解析yyyy-mm-dd

本文探讨了在使用Safari浏览器时遇到的日期格式解析问题。通过对比不同浏览器对日期格式的支持情况,揭示了Safari与Chrome在处理yyyy-mm-dd格式上的差异,并提供了解决方案。

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

一,困惑

昨天写代码遇到的一个bug,在chrome上显示得好好的时间,一到Safari就提示 “invalid date”,于是回来看代码(为了一目了然,进行一些处理):

var deadline = new Date("2016-06-10 23:59");

这行代码是将数据库中存的日期“2016-06-10”字符串转成Date对象。

二,分析

当看到日期格式是yyyy-mm-dd,我联想到了yyyy/mm/dd格式,以前我也好奇这两种格式有什么区别,不过之前用chrome浏览器来测试这两种日期格式,发现并没有什么区别(当初并没有浏览器兼容问题的考虑 - -!)。

于是我猜,会不会是Safari不支持yyyy-mm-dd这种格式,马上改代码:

var date_format = "2016-06-10".split('-').join('/')
var deadline = new Date(date_format + " 23:59");

将yyyy-mm-dd格式转换成yyyy/mm/dd格式后,发现Safari和chrome都没有问题了,看来是浏览器对时间格式支持不太一样。

后来为了验证自己的想法,上stackoverflow上查查,看到了几个类似的问题,这里挑一个有代表性的给大家看看:

Safari JS cannot parse YYYY-MM-DD date format?

大概的意思是说,在执行new Date( string ) 的时候,不同浏览器会采用不同的parse,目前chrome两种格式都支持,而Safari只支持yyyy/mm/dd。

三,end

最近在做前端开发的时候,遇到了不少兼容性问题,后面会不断总结,希望以后少踩坑。

关于css,html的兼容性问题,可以参考这个网站:

can i use
对于像我这样的新手,这个网站具有极高的参考价值,希望也能帮到大家。

caniuse检测css浏览器兼容性问题

import requests from bs4 import BeautifulSoup import time import re import sys from datetime import datetime, timedelta import os # ===== 用戶配置區域 ===== CHECK_INTERVAL = 300 # 檢查間隔(秒),建議300秒(5分鐘) USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36" MONITOR_RANGE = 30 # 監控日期範圍(天數) # ======================= def validate_date(date_str): """驗證日期格式是否為YYYY-MM-DD""" pattern = r'^\d{4}-\d{2}-\d{2}$' return re.match(pattern, date_str) is not None def get_target_dates(): """獲取用戶輸入的目標日期或多個日期""" print("\n" + "="*50) print("澳車北上預約監控程式") print("="*50) while True: print("\n選擇監控模式:") print("1. 監控單一日期") print("2. 監控多個日期") print("3. 監控日期範圍") choice = input("請輸入選擇 (1/2/3): ") if choice == "1": while True: date_input = input("請輸入要監控的日期 (格式: YYYY-MM-DD): ") if validate_date(date_input): return [date_input] print("日期格式錯誤! 請使用YYYY-MM-DD格式重新輸入") elif choice == "2": while True: dates_input = input("請輸入多個日期,用逗號分隔 (格式: YYYY-MM-DD,YYYY-MM-DD): ") date_list = [d.strip() for d in dates_input.split(",")] if all(validate_date(d) for d in date_list): return date_list print("日期格式錯誤! 請確保所有日期都使用YYYY-MM-DD格式") elif choice == "3": while True: start_date = input("請輸入開始日期 (格式: YYYY-MM-DD): ") if not validate_date(start_date): print("開始日期格式錯誤!") continue end_date = input("請輸入結束日期 (格式: YYYY-MM-DD): ") if not validate_date(end_date): print("結束日期格式錯誤!") continue # 確保開始日期早於結束日期 if start_date > end_date: print("錯誤: 開始日期必須早於結束日期!") continue # 生成日期範圍 start = datetime.strptime(start_date, "%Y-%m-%d") end = datetime.strptime(end_date, "%Y-%m-%d") # 限制監控範圍大小 if (end - start).days > MONITOR_RANGE: print(f"警告: 監控範圍超過{MONITOR_RANGE}天,將自動截斷為{MONITOR_RANGE}天") end = start + timedelta(days=MONITOR_RANGE) date_list = [] current = start while current <= end: date_list.append(current.strftime("%Y-%m-%d")) current += timedelta(days=1) print(f"將監控 {len(date_list)} 天: 從 {start_date} 到 {date_list[-1]}") return date_list else: print("無效選擇,請輸入1, 2或3") def check_appointment(): """檢查預約系統獲取所有可用日期""" url = "https://app.vehiclemacau.com.mo/mvcd/booking/appointment" try: headers = {"User-Agent": USER_AGENT} response = requests.get(url, headers=headers, timeout=10) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') date_select = soup.find("select", {"id": "appointmentDate"}) if date_select: available_dates = [option["value"] for option in date_select.find_all("option")] return available_dates return [] except Exception as e: print(f"[ERROR] 檢查失敗: {str(e)}") return [] def print_success_banner(found_dates, all_target_dates): """打印成功監控結果的醒目橫幅""" # 清屏 os.system('cls' if os.name == 'nt' else 'clear') print("\n" + "="*80) print(" " * 30 + "監控結果報告") print("="*80) print(f" 發現時間: \033[1;33m{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\033[0m") # 顯示找到的日期 print("\n\033[1;32m✓ 以下日期已開放預約:\033[0m") for date in found_dates: print(f" - {date}") # 顯示尚未開放的日期 remaining_dates = sorted(set(all_target_dates) - set(found_dates)) if remaining_dates: print("\n\033[1;31m✗ 以下日期尚未開放:\033[0m") for date in remaining_dates: print(f" - {date}") print("="*80) print(" 請立即登錄系統進行預約:") print(" https://app.vehiclemacau.com.mo") print("="*80 + "\n") def monitor(target_dates): print(f"\n開始監控日期: {', '.join(target_dates)}") print(f"監控天數: {len(target_dates)}") print(f"檢查間隔: {CHECK_INTERVAL}秒") print("按 Ctrl+C 停止監控\n") start_time = time.time() check_count = 0 found_dates = set() # 已找到的日期集合 try: while True: current_time = time.strftime('%Y-%m-%d %H:%M:%S') print(f"[{current_time}] 第 {check_count+1} 次檢查...") check_count += 1 # 獲取所有可用日期 available_dates = check_appointment() # 檢查目標日期是否在可用日期中 new_found = False for date in target_dates: if date in available_dates and date not in found_dates: print(f"[SUCCESS] {date} 已開放預約!") found_dates.add(date) new_found = True # 如果有新發現的日期 if new_found: # 顯示成功橫幅 print_success_banner(sorted(found_dates), target_dates) # 計算監控統計 elapsed_time = time.time() - start_time hours, rem = divmod(elapsed_time, 3600) minutes, seconds = divmod(rem, 60) print(f"監控統計:") print(f" - 總檢查次數: {check_count}次") print(f" - 總監控時間: {int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}") print(f" - 最後發現時間: {current_time}") print(f" - 總發現日期: {len(found_dates)}個") # 檢查是否所有日期都已找到 if len(found_dates) == len(target_dates): print("\n\033[1;32m✓ 所有目標日期均已開放預約!\033[0m") break else: print(f" - 剩餘監控日期: {len(target_dates) - len(found_dates)}個") # 顯示當前可用日期 if available_dates: print(f"當前可用日期: {', '.join(available_dates)}") else: print("暫無可用日期") # 倒數計時顯示 for remaining in range(CHECK_INTERVAL, 0, -10): sys.stdout.write(f"\r下次檢查倒數: {remaining}秒 ") sys.stdout.flush() time.sleep(10) print("\n" + "-" * 50) except KeyboardInterrupt: print("\n\n監控程序已手動停止") print(f"總檢查次數: {check_count}次") elapsed_time = time.time() - start_time hours, rem = divmod(elapsed_time, 3600) minutes, seconds = divmod(rem, 60) print(f"總監控時間: {int(hours):02d}:{int(minutes):02d}:{int(seconds):02d}") if found_dates: print(f"已發現的可用日期: {', '.join(sorted(found_dates))}") if __name__ == "__main__": target_dates = get_target_dates() monitor(target_dates) 詳細解釋內容和用途
06-25
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值