- Required NuGet package Spectre.Console
- Place
Prompts.cs
in its own file
Last active
April 18, 2025 15:48
-
-
Save karenpayneoregon/b4b77f1c90d81826a3ee399827e4f318 to your computer and use it in GitHub Desktop.
C# Get date time with hour and minutes in 24h format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace InputsDemo; | |
internal partial class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var value = Prompts.GetDate(); | |
Console.WriteLine(value.Year == 1 ? "Cancelled" : $"Selected date: {value:MM/dd/yyyy HH:mm}"); | |
Console.ReadLine(); | |
} | |
} | |
/// <summary> | |
/// Provides methods for interacting with the user to prompt and retrieve input values. | |
/// </summary> | |
public class Prompts | |
{ | |
/// <summary> | |
/// Prompts the user to enter a date and time in the 24-hour format (DD/MM/YYYY hh:mm) | |
/// and validates the input. | |
/// </summary> | |
/// <returns> | |
/// A <see cref="DateTime"/> representing the user-provided date and time. | |
/// </returns> | |
public static DateTime GetDate() | |
{ | |
return AnsiConsole.Prompt( | |
new TextPrompt<DateTime>("[cyan]Enter Meal Time in the 24h format[/] [b]MM/DD/YYYY hh:mm[/] ") | |
.AllowEmpty() | |
.PromptStyle("cyan") | |
.ValidationErrorMessage("[red]That's not a valid date[/]") | |
.Validate(date => IsTimeIn24HourFormat(date) | |
? ValidationResult.Success() | |
: ValidationResult.Error("[mediumvioletred]Invalid Input, please try a date time value, in 24h, like DD/MM/YYYY hh:mm[/]"))); | |
} | |
/// <summary> | |
/// Validates whether the specified <see cref="DateTime"/> is in the 24-hour time format. | |
/// </summary> | |
/// <param name="dateTime"> | |
/// The <see cref="DateTime"/> to validate. | |
/// </param> | |
/// <returns> | |
/// <c>true</c> if the <paramref name="dateTime"/> represents a valid time in the 24-hour format; otherwise, <c>false</c>. | |
/// </returns> | |
private static bool IsTimeIn24HourFormat(DateTime dateTime) | |
{ | |
var hour = dateTime.Hour; | |
var minute = dateTime.Minute; | |
var isValidHour = hour is >= 0 and <= 23; | |
var isValidMinute = minute is >= 0 and <= 59; | |
return isValidHour && isValidMinute; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment