Advertisement
Codewilly

Untitled

Sep 25th, 2020
1,061
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.26 KB | None | 0 0
  1. using System;
  2. using System.Globalization;
  3.  
  4. namespace DateMergeTime
  5. {
  6.     class Program
  7.     {
  8.         static void Main(string[] args)
  9.         {
  10.             var _date = DateTime.Now;
  11.  
  12.             string[] _horas = { "17:12:1", "161023", "17:20", "17:2", "1720", "172", "17", "xablau" };
  13.  
  14.             foreach (var hora in _horas)
  15.             {
  16.                 Console.WriteLine(_date.SetTimeFromString(hora));
  17.             }
  18.         }
  19.     }
  20.  
  21.     public static class DateTimeHelpers
  22.     {
  23.         public static DateTime SetTimeFromString(this DateTime date, string time)
  24.         {
  25.             return date.WithoutTime() + time.ToTimeSpan();
  26.         }
  27.  
  28.         public static DateTime WithoutTime(this DateTime datetime)
  29.         {
  30.             return new DateTime(datetime.Year, datetime.Month, datetime.Day);
  31.         }
  32.  
  33.         public static TimeSpan ToTimeSpan(this string time)
  34.         {
  35.             time = time.Replace(":", "");
  36.  
  37.             time = time.Length <= 5
  38.                    ? time.PadRight(6, '0')
  39.                    : time;
  40.  
  41.             if (TimeSpan.TryParseExact(time, "hhmmss", CultureInfo.InvariantCulture, out TimeSpan parsedTime))
  42.                 return parsedTime;          
  43.  
  44.             return new TimeSpan();
  45.         }
  46.     }
  47. }
  48.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement