C#:DateTime.DayOfWeek字符串比较 [英] C#: DateTime.DayOfWeek to string comparison

查看:283
本文介绍了C#:DateTime.DayOfWeek字符串比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这代码是什么,我试图做一个简化版本:

This code is a simplified version of what I'm trying to do:

string day = Thursday;
DateTime dt = DateTime.Now;

if (day == dt.DayOfWeek)
{
     // start the program
}

我需要从数据库中读取的周值的日子,将其分配给一个字符串,然后比较字符串dt.DayOfWeek检查程序应该执行。

I need to read a day of the week value from a database, assign it to a string, then compare the string to dt.DayOfWeek to check if the program should execute.

我的错误是这样的:运算符'=='不能应用于类型为'字符串'和'System.DayOfWeek的操作数

任何人都知道如何将字符串比作DateTime.DayOfWeek价值?

Anyone know how to compare a string to a DateTime.DayOfWeek value?

推荐答案

最简单的就是枚举转换为字符串:

Easiest is to convert enum to string:

if (day == dt.DayOfWeek.ToString())...

注:


  • 如果你可以改变的类型星期几枚举可以避开字符串比较(及其相关的本地化/比较问题)。

  • 如果你必须使用字符串确保来决定,如果情况是很重要与否(即应该星期四等于 DayOfWeek.Thursday ),并使用相应的 String.Equals 方法。

  • 考虑转换字符串枚举与解析在其他的答案提示:((星期几)Enum.Parse(typeof运算(星期几),日)

  • 确保输入的字符串始终是英语 - 如果它可以在其他语言中,你需要寻找到匹配手动价值之一的 CultureInfo.DateTimeFormat.DayNames

  • if you can change type of day to DayOfWeek enum you can avoid string comparisons (and its related localization/comparison issues).
  • if you have to use string make sure to decide if case is important or not (i.e. should "thursday" be equal to DayOfWeek.Thursday) and use corresponding String.Equals method.
  • consider converting string to enum with Parse as suggested in other answers: ((DayOfWeek)Enum.Parse(typeof(DayOfWeek), day)
  • make sure incoming string is always English - if it could be in other languages you'll need to look into manually matching value to one provided in CultureInfo.DateTimeFormat.DayNames.

这篇关于C#:DateTime.DayOfWeek字符串比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆