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

如何在Swift中从日期获取指定格式的星期几?

获取缩写星期几(如Mon)的实现方法

嘿,这个问题其实挺常见的,我来给你拆解一下不同主流编程语言里的实现方式,你可以对应自己使用的语言来参考:

Python 实现

在Python里,datetime模块能轻松搞定这个需求:

  • 如果已经有一个日期对象,直接用strftime()方法指定格式符%a就能拿到缩写星期几:
from datetime import datetime

# 示例:从现有日期对象获取
current_date = datetime(2018, 3, 19)
weekday_abbr = current_date.strftime("%a")
print(weekday_abbr)  # 输出: Mon
  • 如果是从字符串「Mon, Mar 19, 2018」解析出星期几,也可以先转成日期对象再提取:
date_str = "Mon, Mar 19, 2018"
date_obj = datetime.strptime(date_str, "%a, %b %d, %Y")
weekday_abbr = date_obj.strftime("%a")
print(weekday_abbr)  # 输出: Mon

这里的%a对应本地语言环境的缩写星期名称,如果需要固定英文格式,可以指定对应的locale参数。

JavaScript 实现

在JS里,Date对象有两种常用方式实现:

  • 方法1:用toLocaleDateString配合参数直接生成:
const date = new Date(2018, 2, 19); // 注意JS月份从0开始,3月对应数字2
const weekdayAbbr = date.toLocaleDateString('en-US', { weekday: 'short' });
console.log(weekdayAbbr); // 输出: Mon
  • 方法2:手动映射(适合需要完全自定义缩写的场景):
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const date = new Date(2018, 2, 19);
const weekdayAbbr = weekdays[date.getDay()];
console.log(weekdayAbbr); // 输出: Mon

Java 实现

Java里推荐用Java 8+的新日期API,也支持旧版的SimpleDateFormat:

// Java 8+ 推荐方式
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        LocalDate date = LocalDate.of(2018, 3, 19);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE");
        String weekdayAbbr = date.format(formatter);
        System.out.println(weekdayAbbr); // 输出: Mon
    }
}

// 旧版SimpleDateFormat方式
import java.text.SimpleDateFormat;
import java.util.Date;

public class Main {
    public static void main(String[] args) {
        Date date = new Date(118, 2, 19); // 年份需减去1900,3月对应数字2
        SimpleDateFormat sdf = new SimpleDateFormat("EEE");
        String weekdayAbbr = sdf.format(date);
        System.out.println(weekdayAbbr); // 输出: Mon
    }
}

核心思路其实都是:利用日期处理库的格式化功能,指定对应缩写星期的格式标识,不同语言的格式符略有差异,但逻辑一致。如果你的场景有特定语言环境需求,记得设置对应的locale参数哦!

内容的提问来源于stack exchange,提问作者S.S.D

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:57:03