Created
January 6, 2026 03:59
-
-
Save karenpayneoregon/fa6c686eccbab7f1759e651144edd43c to your computer and use it in GitHub Desktop.
Spectre.Console get date time in 24 hour 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
| internal partial class Program | |
| { | |
| static void Main(string[] args) | |
| { | |
| var value = Prompts.GetDate(); | |
| Console.WriteLine(value.Year == 1 ? "Cancelled" : $"Selected date: {value:dd/MM/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]DD/MM/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