Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Globalization;
- namespace DateMergeTime
- {
- class Program
- {
- static void Main(string[] args)
- {
- var _date = DateTime.Now;
- string[] _horas = { "17:12:1", "161023", "17:20", "17:2", "1720", "172", "17", "xablau" };
- foreach (var hora in _horas)
- {
- Console.WriteLine(_date.SetTimeFromString(hora));
- }
- }
- }
- public static class DateTimeHelpers
- {
- public static DateTime SetTimeFromString(this DateTime date, string time)
- {
- return date.WithoutTime() + time.ToTimeSpan();
- }
- public static DateTime WithoutTime(this DateTime datetime)
- {
- return new DateTime(datetime.Year, datetime.Month, datetime.Day);
- }
- public static TimeSpan ToTimeSpan(this string time)
- {
- time = time.Replace(":", "");
- time = time.Length <= 5
- ? time.PadRight(6, '0')
- : time;
- if (TimeSpan.TryParseExact(time, "hhmmss", CultureInfo.InvariantCulture, out TimeSpan parsedTime))
- return parsedTime;
- return new TimeSpan();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement