检查日期时间字符串是否包含时间
本文关键字:时间 包含 是否 字符串 检查 日期 | 更新日期: 2023-09-27 18:08:23
我遇到了一个问题。我正在从数据库中获取一个日期时间字符串并且其中一些日期时间字符串不包含时间。但是对于新的要求,每个日期时间字符串应该包含这样的时间,
1) 1980/10/11 12:00:01
2) 2010/APRIL/02 17:10:00
3) 10/02/10 03:30:34
日期可以是任意格式,后面跟着24hr
表示法中的时间。
我试图通过下面的代码来检测时间的存在,
string timestamp_string = "2013/04/08 17:30";
DateTime timestamp = Convert.ToDateTime(timestamp_string);
string time ="";
if (timestamp_string.Length > 10)
{
time = timestamp.ToString("hh:mm");
}
else {
time = "Time not registered";
}
MessageBox.Show(time);
但这只适用于No 1)
类型的时间戳。我可以知道如何实现这个任务,如何检测时间元素是否存在于这个日期时间字符串。非常感谢:)
可能的匹配如何验证"日期和时间"弦只有时间?
INFO Arun Selva Kumar
, Guru Kara
, Patipol Paripoonnanonda
提供的三个答案都是正确的,符合我的目的。但我选择Guru Kara
的答案仅仅是因为易用性和他给出的解释。非常感谢:)非常感谢大家:)
日期时间组件TimeOfDay是您需要的。
MSDN说"不像Date属性,它返回一个DateTime值,表示一个没有时间组件的日期,TimeOfDay属性返回一个TimeSpan值,表示一个DateTime值的时间组件。"
这是一个考虑到所有场景的例子。
既然你确定格式,你可以使用DateTime.Parse
,否则请使用DateTime.TryParse
var dateTime1 = System.DateTime.Parse("1980/10/11 12:00:00");
var dateTime2 = System.DateTime.Parse("2010/APRIL/02 17:10:00");
var dateTime3 = System.DateTime.Parse("10/02/10 03:30:34");
var dateTime4 = System.DateTime.Parse("02/20/10");
if (dateTime1.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("1980/10/11 12:00:00 - does not have Time");
} else {
Console.WriteLine("1980/10/11 12:00:00 - has Time");
}
if (dateTime2.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("2010/APRIL/02 17:10:00 - does not have Time");
} else {
Console.WriteLine("2010/APRIL/02 17:10:00 - Has Time");
}
if (dateTime3.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("10/02/10 03:30:34 - does not have Time");
} else {
Console.WriteLine("10/02/10 03:30:34 - Has Time");
}
if (dateTime4.TimeOfDay.TotalSeconds == 0) {
Console.WriteLine("02/20/10 - does not have Time");
} else {
Console.WriteLine("02/20/10 - Has Time");
}
试试这个,
DateTime myDate;
if (DateTime.TryParseExact(inputString, "dd-MM-yyyy hh:mm:ss",
CultureInfo.InvariantCulture, DateTimeStyles.None, out myDate))
{
//String has Date and Time
}
else
{
//String has only Date Portion
}
您可以尝试使用这里列出的其他格式说明符http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
将Guru Kara和Patipol Paripoonnanonda的答案与。net全球化API相结合,结果是:
bool HasExplicitTime(DateTime parsedTimestamp, string str_timestamp)
{
string[] dateTimeSeparators = { "T", " ", "@" };
string[] timeSeparators = {
CultureInfo.CurrentUICulture.DateTimeFormat.TimeSeparator,
CultureInfo.CurrentCulture.DateTimeFormat.TimeSeparator,
":"};
if (parsedTimestamp.TimeOfDay.TotalSeconds != 0)
return true;
string[] dateOrTimeParts = str_timestamp.Split(
dateTimeSeparators,
StringSplitOptions.RemoveEmptyEntries);
bool hasTimePart = dateOrTimeParts.Any(part =>
part.Split(
timeSeparators,
StringSplitOptions.RemoveEmptyEntries).Length > 1);
return hasTimePart;
}
这种方法:
- 检测明确的午夜时间(例如:"2015 - 02 - 26 t00:00");
- 只在
TimeOfDay
表示午夜或没有明确时间时搜索字符串;和 - 查找本地格式的显式午夜时间和。net可以解析的任何格式的任何非午夜时间。
限制:
- 未检测到非区域性本地格式的
- 显式午夜时间;
- 明确午夜时间少于两个部分未被检测到;和
- 不像Guru Kara和Patipol Paripoonnanonda的方法那么简单和优雅。
这是我现在要做的。这可能不是完美的,但总比认为任何一个约会时间都是没有时间要好。前提是,如果我在末尾添加一个完整的时间规范,它将解析它是否只是一个日期,但如果它已经包含时间组件,则会失败。
我不得不假设没有有效的日期/时间包含7个或更少的非空白字符。可以解析"1980/10",但不能解析"1980/10 01:01:01.001"。
我已经包含了各种测试用例。请随意添加你自己的,如果它们失败了请告诉我。
public static bool IsValidDateTime(this string dateString, bool requireTime = false)
{
DateTime outDate;
if(!DateTime.TryParse(dateString, out outDate)) return false;
if (!requireTime) return true;
else
{
return Regex.Replace(dateString, @"'s", "").Length > 7
&& !DateTime.TryParse(dateString + " 01:01:01.001", out outDate);
}
}
public void DateTest()
{
var withTimes = new[]{
"1980/10/11 01:01:01.001",
"02/01/1980 01:01:01.001",
"1980-01-01 01:01:01.001",
"1980/10/11 00:00",
"1980/10/11 1pm",
"1980-01-01 00:00:00"};
//Make sure our ones with time pass both tests
foreach(var date in withTimes){
Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date));
Assert.IsTrue(date.IsValidDateTime(true), String.Format("date: {0} does have time.", date));
}
var withoutTimes = new[]{
"1980/10/11",
"1980/10",
"1980/10 ",
"10/1980",
"1980 01",
"1980/10/11 ",
"02/01/1980",
"1980-01-01"};
//Make sure our ones without time pass the first and fail the second
foreach (var date in withoutTimes)
{
Assert.IsTrue(date.IsValidDateTime(), String.Format("date: {0} isn't valid.", date));
Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} doesn't have time.", date) );
}
var bogusTimes = new[]{
"1980",
"1980 01:01",
"80 01:01",
"1980T01",
"80T01:01",
"1980-01-01T01",
};
//Make sure our ones without time pass the first and fail the second
foreach (var date in bogusTimes)
{
DateTime parsedDate;
DateTime.TryParse(date, out parsedDate);
Assert.IsFalse(date.IsValidDateTime(), String.Format("date: {0} is valid. {1}", date, parsedDate));
Assert.IsFalse(date.IsValidDateTime(true), String.Format("date: {0} is valid. {1}", date, parsedDate));
}
}
这是否适用于您的用例:
bool noTime = _datetimevalue.TimeOfDay。Ticks == 0;
如果DateTime实例中不存在时间组件,Ticks将为0。
日期和时间总是用空格分隔。最简单的方法是:
if (timestamp_string.Split(' ').Length == 2)
{
// timestamp_string has both date and time
}
else
{
// timestamp_string only has the date
}
此代码假设日期始终存在。
如果你想更进一步(如果日期不存在),你可以这样做:
if (timestamp_string.Split(' ')
.Select(item => item.Split(':').Length > 1)
.Any(item => item))
{
// this would work for any string format that contains date, for example:
// 2012/APRIL/03 12:00:05 -> this would work
// 2013/04/05 09:00:01 -> this would work
// 08:50:45 2013/01/01 -> this would also work
// 08:50:50 -> this would also work
}
else
{
// no date in the timestamp_string at all
}
希望这对你有帮助!