I wrote a code for converting string value to TimeSpan value.
Sometimes it has FormatException not always. It is usually works well.
To subtract string as time, I used DateTime.Parse for each string value.
TimeSpan timespan = DateTime.Parse(logs_temp[i + 1].time).Subtract(DateTime.Parse(logs_temp[i].time));
It is my part of code.
public class log
{
[XmlElement("command")]
public int command { get; set; }
[XmlElement("param")]
public int param { get; set;}
[XmlElement("time")]
public string time { get; set; }
}
List<log> logs = logs_temp.ToList();
// logs and logs_temp have same command and param item. However add timespan bewteewn two commands in
// time item
for (int i = 0; i <= logs_temp.Count - 1; i++)
{
logs[i].command = logs_temp[i].command;
logs[i].param = logs_temp[i].param;
//Get a timespan between two sequencial command log
if (i + 1 < logs_temp.Count)
{ // I could find Format exception there
TimeSpan timespan = DateTime.Parse(logs_temp[i + 1].time).Subtract(DateTime.Parse(logs_temp[i].time));
//add second value as string but cannot
logs[i].time = timespan.TotalSeconds.ToString();
}
}
DateTime.Parse tries to parse it using the current PC culture. If it can't it will throw the format exception. So I guess your supplied time string is different sometimes. So set a break point to check.
Best would be to use DateTime.TryParseExact or the
dateString = "05/01/2009 01:30:42 PM -05:00";
if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None, out dateValue))
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
else
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
Related
How can the method be implemented in C#?
string StartTime = "06:10 PM";
string Endtime = "08:10 PM";
DateTime current_time = DateTime.Now;
bool validTime = validTimeFindout(StartTime,Endtime,current_time);
bool validTimeFindout(string StartTime, string Endtime,DateTime current_time){
// This method should return true
// when the current_time>= StartTime && current_time<=Endtime
// otherwise false
}
I tried to find out the valid time in the specific range and for that validTimeFindout method will help and here the method is comparing the time get from local pc and compare them with StartTime and Endtime
Starting with .NET 6, you can use the TimeOnly Struct:
static bool IsTimeBetween(string startTime, string endTime, DateTime dateTime)
{
if (TimeOnly.TryParse(startTime, out var t1) &&
TimeOnly.TryParse(endTime, out var t2))
{
return TimeOnly.FromDateTime(dateTime).IsBetween(t1, t2);
}
return false;
}
Note that TimeOnly.IsBetween supports time ranges that span midnight such as 23:00-01:00.
You can use DateTime.TryParse() method to parse a string into the DateTime datatype.
DateTime datatypes can be compared as numeric datatypes with <, <=, ==, !=, >=, >
bool validTimeFindout(string StartTime, string Endtime, DateTime current_time){
DateTime start;
DateTime.TryParse(StartTime, out start);
DateTime end;
DateTime.TryParse(Endtime, out end);
return current_time >= start && current_time <= end;
}
You just need to convert the inputs from string to datetime and do the calculations: datetime.parse()
bool validTimeFindout(string StartTime, string Endtime, DateTime current_time)
{
DateTime _startTime = DateTime.Parse(StartTime);
DateTime _endTime = DateTime.Parse(Endtime);
if (current_time >= _startTime && current_time <= _endTime)
return true;
else
return false;
}
First you need to convert those strings to DateTime objects.
Then you should compare those DateTime objects and current time.
using System.Globalization;
string StartTime = "06:10 PM";
string Endtime = "08:10 PM";
DateTime current_time = DateTime.Now;
try {
bool validTime = validTimeFindout(StartTime, Endtime, current_time);
Console.WriteLine(validTime);
}catch(Exception exc) {
Console.WriteLine(exc.Message);
}
bool validTimeFindout(string StartTime, string Endtime, DateTime current_time) {
DateTime start = ParseTimeString(StartTime);
DateTime end = ParseTimeString(Endtime);
if(current_time.CompareTo(start) >= 0 && current_time.CompareTo(end) <= 0) {
return true;
} else {
return false;
}
}
DateTime ParseTimeString(string timeString) {
string format = "hh:mm tt";
DateTime result;
if (DateTime.TryParseExact(timeString, format, CultureInfo.GetCultureInfo("en-US"), DateTimeStyles.None, out result)) {
return result;
} else {
throw new Exception("Cannot parse time!");
}
}
There are also several things you can rethink and fix.
Naming pattern - IMHO is valid is not a good name for method checking if a DateTime is between other DateTimes.
Use single naming convention and stick to it. The most popular convention in C# is cammel case (like startTime).
Is it really needed to store those DateTimes in strings formatted like "01:10 PM"? Why doesn't you simply store DateTime objects?
I need to accept input paramteters and print date range in console like in the example:
input: "01.01.2017 05.01.2017"
output: "01 - 05.01.2017"
So as you see dates must be separated with dots and printed with dash between them. What is more, if start and end date both has the same month and year, these are printed only once.
Does anyone can suggest good way to achieve this?
Just format date as you need and add aditional check for cases.
DateTime date1 = new DateTime();
DateTime date2 = new DateTime();
//while not valid input dates format...
bool valid = false;
while (!valid)
{
Console.WriteLine("Enter start date:");
string dateEntered1 = Console.ReadLine();
Console.WriteLine("Enter end date:");
string dateEntered2 = Console.ReadLine();
bool isvalidDate1 = DateTime.TryParse(dateEntered1,out date1);
bool isvalidDate2 = DateTime.TryParse(dateEntered2,out date2);
//check if date parsing was sucess
if(isvalidDate1 && isvalidDate2)
{
valid = true;
}
else
{
Console.WriteLine("Dates entered is in incorrect format!");
}
}
string period = "";
if (date1.Month == date2.Month && date1.Year == date2.Year)
{
period = string.Format("{0} - {1}", date1.ToString("dd."), date2.ToString("dd.MM.yyyy"));
}
else
{
period = string.Format("{0} - {1}", date1.ToString("dd.MM.yyyy"), date2.ToString("dd.MM.yyyy"));
}
Console.Write(period);
Console.Read();
I have a string in a format like 22 : 19 : 37 where 22 is Days, 19 is hours and 37 is minutes, this is what I have written to validate Hour and Minutes.
string value = "22 : 19 : 37";
string[] time = (value as string).Split(new char[] { ':' });
if (time.Length != 3)
{
Console.WriteLine("Error");
return;
}
int DD = System.Convert.ToInt32(time[0]);
int HH = System.Convert.ToInt32(time[1]);
int MM = System.Convert.ToInt32(time[2]);
// Hour should be less than 24
if (HH > 23)
{
Console.WriteLine("Invalid Hour Error");
return;
}
// Minutes should be less than 60
if (MM > 59)
{
Console.WriteLine("Invalid Minute Error");
return;
}
I don't like the code, is there anyway to improve this.
DateTime.TryParse This I believe is faster and it means you don't have to use try/catches.
e.g:
DateTime temp;
if(DateTime.TryParse(yourString, out temp))
//yay
else
// :(
Try this
string dateString = "22 : 19 : 37";
string format = "dd : HH : mm";
DateTime result;
var provider = System.Globalization.CultureInfo.InvariantCulture;
try {
result = DateTime.ParseExact(dateString, format, provider);
Console.WriteLine("{0} converts to {1}.", dateString, result.ToString());
}
catch (FormatException) {
Console.WriteLine("{0} is not in the correct format.", dateString);
}
As this appears to be a TimeSpan rather than a DateTime, here is the variant of #Nkosi. Also using TryParseExact rather than ParseExact. It gets rid of the ugly try catch.
string timeSpanString = "22 : 19 : 37";
// For TimeSpan parsing all separator values need to be escaped with \\
string timeSpanFormat = "dd\\ \\:\\ hh\\ \\:\\ mm";
TimeSpan result;
var provider = System.Globalization.CultureInfo.InvariantCulture;
if (TimeSpan.TryParseExact(timeSpanString, timeSpanFormat, provider, out result))
{
Console.WriteLine("{0} converts to {1}.", timeSpanString, result);
}
else
{
Console.WriteLine("{0} is not in the correct format.", timeSpanString);
}
I think this shows the intent more clearly as #Nkosi code will output the data with a year an month.
I agree with #user3378165. But if cant change your string format you can use a regex expression to check if your string is a valid time string in format HH:MM:SS
A regular expression for this:
^\d{2}:([0-1]\d|2[0-3]):([0-5]\d)$
Next, use Regex object to do the checking
So I've got a string 00:00:15:185 which I need to tell is greater than 15 seconds.
Time format is HH:m:ss:FFF
This is clearly longer than 15 seconds but I can't compare it properly.
Current code is this:
value = "00:00:15:185";
if (DateTime.Parse(value) > DateTime.Parse("00:00:15:000"){
//do stuff
}
It's giving exceptions when I run it all the time and the program doesn't work when it should
Your string doesn't represent a time, but an amount of time. We have TimeSpan for that.
var value = "00:00:15:185";
if (TimeSpan.ParseExact(value, #"hh\:mm\:ss\:FFF", CultureInfo.InvariantCulture)
> TimeSpan.FromSeconds(15))
{
//do stuff
}
Another option(apart from #rob 's answer), use DateTime.ParseExact
var value = "00:00:15:185";
if (DateTime.ParseExact(value, "HH:mm:ss:fff", CultureInfo.InvariantCulture) >
DateTime.ParseExact("00:00:15:000", "HH:mm:ss:fff", CultureInfo.InvariantCulture))
{
// logic here.
}
DateTime time = DateTime.Now;
String result = time.ToString("HH:mm ");
DateTime firstTimr = DateTime.ParseExact(reader["shift_start_time"].ToString(), "HH:mm:tt", null);
String firstTimr1 = firstTimr.ToString("HH:mm ");
DateTime lastTime = DateTime.ParseExact(reader["Shift_last_time"].ToString(), "HH:mm:tt", null);
String lastTime1 = lastTime.ToString("HH:mm ");
if (DateTime.Parse(result) >= DateTime.Parse(firstTimr1) && (DateTime.Parse(result) <= DateTime.Parse(lastTime1)))
{
`enter code here` MessageBox.Show("First Shit");
}
I have a scenario where I need to parse strings representing datetimes.
The length of the string implies the precision:
"2012-11-11" represents any moment in "november 11 of 2012"
"2012-11" represents any moment in "november of 2012"
"2012-11-11 10:11" represents any seconds in that minute
I would need to parse these strings as ranges of time.
Is there a datastructure that can help representing this or do I need to parse it manually and use 2 DateTimes.
You will have to write your own class to manage this.
Let's assume that your date strings are always in one of the following formats:
yyyy-M-d HH:mm:ss
yyyy-M-d HH:mm
yyyy-M-d HH
yyyy-M-d
yyyy-M
yyyy
Then you can write a class to encapsulate this as follows:
public sealed class TimeRange
{
public TimeRange(string dateTimeString)
{
DateTime dateTime;
if (DateTime.TryParseExact(dateTimeString, #"yyyy-M-d HH\:mm\:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddSeconds(1);
}
else if (DateTime.TryParseExact(dateTimeString, #"yyyy-M-d HH\:mm", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddMinutes(1);
}
else if (DateTime.TryParseExact(dateTimeString, #"yyyy-M-d HH", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddHours(1);
}
else if (DateTime.TryParseExact(dateTimeString, #"yyyy-M-d", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddDays(1);
}
else if (DateTime.TryParseExact(dateTimeString, #"yyyy-M", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddMonths(1);
}
else if (DateTime.TryParseExact(dateTimeString, #"yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out dateTime))
{
_start = dateTime;
_end = dateTime.AddYears(1);
}
else
{
throw new ArgumentException("date/time is invalid: " + dateTimeString, "dateTimeString");
}
}
public DateTime Start
{
get
{
return _start;
}
}
public DateTime ExclusiveEnd
{
get
{
return _end;
}
}
private readonly DateTime _start;
private readonly DateTime _end;
}
Note that for simplicity the end of the range, ExclusiveEnd, is expressed as an exclusive range. That means you'd make comparisons like:
if (timeRange.Start <= targetDateTime && targetDateTime < timeRange.ExclusiveEnd)
...
rather than the following, which would be incorrect:
if (timeRange.Start <= targetDateTime && targetDateTime <= timeRange.ExclusiveEnd)
...
Note the difference between < timeRange.ExclusiveEnd and <= timeRange.ExclusiveEnd
To avoid this subtlety you could add to the class a Contains(DateTime) method like:
public bool Contains(DateTime target)
{
return (_start <= target) && (target < _end);
}
A DateTime doesn't represent a period of time, it represents a specific moment in time.
You could use DateTime.TryParse() to parse the string however the interpretation of that is up to you.
https://msdn.microsoft.com/en-us/library/system.datetime.tryparse%28v=vs.110%29.aspx
Example
string foo = "11 August 2016";
DateTime bar = DateTime.Now;
DateTime.TryParse(foo, out bar);
Console.WriteLine(bar.ToString());
will output 11/08/2016 00:00:00
so you could assume this represents any time from 11/08/2016 to 11/08/2016 23:59:59 although it will miss out the case where the time specified was specifically 11/08/2016 00:00:00. Is this a likely input??
Could you gave a bit more info on why you need to interpret it this way?