查找当前时间是否落在时间范围内

时间:2009-10-01 15:02:53

标签: c# datetime timespan

使用.NET 3.5

我想确定当前时间是否落在时间范围内。

到目前为止,我的目标是:

DateTime currentTime = new DateTime();
currentTime.TimeOfDay;

我正在消除如何获得转换和比较的时间范围。 这会有用吗?

if (Convert.ToDateTime("11:59") <= currentTime.TimeOfDay 
    && Convert.ToDateTime("13:01") >= currentTime.TimeOfDay)
{
   //match found
}

更新1:感谢大家的建议。我不熟悉TimeSpan功能。

10 个答案:

答案 0 :(得分:219)

检查一天中的使用时间:

TimeSpan start = new TimeSpan(10, 0, 0); //10 o'clock
TimeSpan end = new TimeSpan(12, 0, 0); //12 o'clock
TimeSpan now = DateTime.Now.TimeOfDay;

if ((now > start) && (now < end))
{
   //match found
}

对于绝对时间使用:

DateTime start = new DateTime(2009, 12, 9, 10, 0, 0)); //10 o'clock
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0)); //12 o'clock
DateTime now = DateTime.Now;

if ((now > start) && (now < end))
{
   //match found
}

答案 1 :(得分:91)

这里有一些好的答案,但没有一个涵盖你的开始时间与你的结束时间不同的一天。如果你需要跨越日界,那么这样的事情可能会有所帮助:

TimeSpan start = TimeSpan.Parse("22:00"); // 10 PM
TimeSpan end = TimeSpan.Parse("02:00");   // 2 AM
TimeSpan now = DateTime.Now.TimeOfDay;

if (start <= end)
{
    // start and stop times are in the same day
    if (now >= start && now <= end)
    {
        // current time is between start and stop
    }
}
else
{
    // start and stop times are in different days
    if (now >= start || now <= end)
    {
       // current time is between start and stop
    }
}

请注意,在此示例中,时间边界是包含的,并且假设startstop之间的差异小于24小时。

答案 2 :(得分:16)

if (new TimeSpan(11,59,0) <= currentTime.TimeOfDay && new TimeSpan(13,01,0) >=  currentTime.TimeOfDay)
{
   //match found
}

如果你真的想要将字符串解析为TimeSpan,那么你可以使用:

    TimeSpan start = TimeSpan.Parse("11:59");
    TimeSpan end = TimeSpan.Parse("13:01");

答案 3 :(得分:13)

尝试在C#中使用TimeRange对象来完成目标。

TimeRange timeRange = new TimeRange();
timeRange = TimeRange.Parse("13:00-14:00");

bool IsNowInTheRange = timeRange.IsIn(DateTime.Now.TimeOfDay);
Console.Write(IsNowInTheRange);

Here is where I got that example of using TimeRange

答案 4 :(得分:13)

一个简单的小扩展功能:

public static bool IsBetween(this DateTime now, TimeSpan start, TimeSpan end)
{
    var time = now.TimeOfDay;
    // If the start time and the end time is in the same day.
    if (start <= end)
        return time >= start && time <= end;
    // The start time and end time is on different days.
    return time >= start || time <= end;
}

答案 5 :(得分:6)

TimeOfDay property会返回TimeSpan值。

请尝试以下代码:

TimeSpan time = DateTime.Now.TimeOfDay;

if (time > new TimeSpan(11, 59, 00)        //Hours, Minutes, Seconds
 && time < new TimeSpan(13, 01, 00)) {
    //match found
}

此外,new DateTime()DateTime.MinValue相同,并且始终等于1/1/0001 12:00:00 AM。 (值类型不能包含非空的默认值)您想使用DateTime.Now

答案 6 :(得分:2)

你非常接近,问题是你正在将DateTime与TimeOfDay进行比较。您需要做的是将.TimeOfDay属性添加到Convert.ToDateTime()函数的末尾。

答案 7 :(得分:1)

处理日边界案件会更简单吗? :)

from collections import defaultdict, Counter
with open('filename.txt') as f:
    text = f.read()
    letter_count = Counter(c for c in text if c.isalpha())

答案 8 :(得分:0)

使用Linq,我们可以通过这个来简化它

 Enumerable.Range(0, (int)(to - from).TotalHours + 1)
            .Select(i => from.AddHours(i)).Where(date => date.TimeOfDay >= new TimeSpan(8, 0, 0) && date.TimeOfDay <= new TimeSpan(18, 0, 0))

答案 9 :(得分:0)

import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:myapp/pages/login_page.dart';
import 'package:myapp/pages/dashboard_page.dart';
import 'package:myapp/styles/constants.dart';
import 'package:myapp/services/auth_service.dart';

Future<void> main() async {
  // create a auth service instance
  AuthService authService = AuthService(secureStorage: FlutterSecureStorage());
  bool isLoggedIn = await authService.isUserLoggedIn();

  // run the app
  runApp(MyApp(
    isLoggedIn: isLoggedIn,
  ));
}

class MyApp extends StatefulWidget {
  final bool isLoggedIn;

  MyApp({this.isLoggedIn});

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> with RouteAware {
  final RouteObserver<PageRoute> routeObserver = RouteObserver<PageRoute>();

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    routeObserver.subscribe(this, ModalRoute.of(context));
  }

  @override
  void dispose() {
    routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    print('didPush');
  }

  @override
  void didPopNext() {
    print('didPopNext');
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App NAME',
      theme: ThemeData(
        primarySwatch: Colors.green,
        primaryColor: kPrimeColour,
      ),
      home: widget.isLoggedIn == true ? DashboardPage() : LoginPage(),
      navigatorObservers: [routeObserver],
    );
  }
}