I want to compare values of two comboboxes. The variables are of type var and they come like this: 27-12-2018
I want to compare these two values and for this purpose I have converted the value in date format and in string format.
This is meteorologycal charts.
var formattedDates = string.Join("_", Path.GetFileName(file).Split('_', '.').Skip(1).Take(3));
var formattedDates2 = string.Join("_", Path.GetFileName(file).Split('_', '.').Skip(1).Take(3));
if (!comboBox2.Items.Contains(formattedName))
{
comboBox2.Items.Add(formattedName);
}
if (!comboBox3.Items.Contains(formattedDates))
{
comboBox3.Items.Add(formattedDates);
}
if (!comboBox4.Items.Contains(formattedDates2))
{
comboBox4.Items.Add(formattedDates2);
}
listBox1.Items.Add(Path.GetFileName(file));
}
}
else
{
MessageBox.Show("Директорията Meteo не е октирта в системен диск 'C:\'");
Application.ExitThread();
}
var result = Directory
.EnumerateFiles(#"C:\Meteo", "*.dat")
.SelectMany(file => File.ReadLines(file))
.Select(line => line.Split(new char[] { '\t', ' ' }, StringSplitOptions.RemoveEmptyEntries))
.Select(items => new {
id = items[0],
date = DateTime.ParseExact(items[1], "dd-MM-yyyy", CultureInfo.InvariantCulture).ToString(),
date2 = items[1],
hours = items[2],
temperature = items[3],
presure = items[4],
windSpeed = items[5],
windDirect = items[6],
rain = items[7],
rainIntensity = items[8],
sunRadiation = items[12],
/* etc. */
})
.ToList();
var dates = result
.Select(item => item.date)
.ToArray();
I have the same values in two formats - String and Date, but I dont know how to compare two comboboxes (if firstCombo > secondCombo){ messagebox.show("")}
Convert your string to a DateTime type.
DateTime DT1 = DateTime.ParseExact("18/08/2015 06:30:15.006542", "dd/MM/yyyy HH:mm:ss.ffffff", CultureInfo.InvariantCulture);
Rearrange the format string to match whatever date format you are using.
Then you can just do:
if(DT1 > DT2)
Also FYI, VAR isnt a type, it just sets the type of the variable to whatever type is on the right side of the equals.
To compare values of two comboboxes, you first need to convert both values into a type that can be compared. In your case, you seem to want to compare dates.
Ex: 07-06-2019 > 06-06-2019 = True.
I would recommend you to get the current values from both comboboxes (combobox.Text) and create a DateTime object with them.
Then, you'll be able to compare them like you want.
DateTime date0 = Convert.ToDateTime(combobox0.Text);//"07-06-2019"
DateTime date1 = Convert.ToDateTime(combobox1.Text);//"06-06-2019"
int value = DateTime.Compare(date0, date1);
if (value > 0)
{
//date0 > date1
}
else
{
if (value < 0)
{
//date0 < date1
}
else
{
//date0 == date1
}
}
Finally, to answer your question, the best practice to compare combobox values is depending on what value you're trying to compare... If you want to compare dates like in your example, it is better to convert the values to DateTime. The only comparison you can make with strings, correct me if I'm wrong, is to check if the strings are equal or have the same value.
Another good practice is to use the TryParse method associated to the type of value you want to convert/compare. Most of, if not all, basic types in c# have this method associated to them.
https://learn.microsoft.com/en-us/dotnet/api/system.datetime.tryparse?view=netframework-4.8
DateTime date0;
//Take text from combobox0, convert it and put the result in date0
bool success = DateTime.TryParse(combobox0.Text, out date0);
if(success)
{
//Your date has been converted properly
//Do stuff
}
Related
By default, DynamoDB converts .NET DateTime to a string type (S) and stores dates in ISO-8601 format. See supported data types. The problem is .NET captures 7 digits for ticks whereas ISO-8601 stores 3. So, if I were to store a DateTime, fetch the entity, and compare the .NET date to what is fetched (for example in a test), this will fail.
TimeOfDay comparisons:
15:28:21.4731507 (.NET)
15:28:21.473 (DynamoDB)
Another problem I see is the DynamoDB SDK will convert UTC to local time when items are being retrieved. See a reported issue with a workaround. The suggested fix does not work for me. The converter will successfully convert the date via ToUniversalTime(), but it seems the returned value is being ignored. Thus, I still get a local time.
I'd like to avoid storing dates in ISO-8601. I know that I can store the ticks as a long property in my entities. This eliminates both problems described above. The caveat is I won't be able to use a DateTime property type anywhere in my entities going forward.
This brings me to my question. Is it possible to override the default SDK behavior so that DateTime is stored as a number type (N) in DynamoDB?
To address the issue of truncated ticks, you can use the "o" date format string, which is the "round trip" date format, for this exact scenario. The GitHub example wasn't specifying a format in its ToEntry lambda, so I believe it was further truncating information when ToString() was then called without any format information.
You can modify the sample in GitHub like so:
public class CustomDateTimeConverter : IPropertyConverter
{
public DynamoDBEntry ToEntry(object value)
{
DateTime? dateTimeValue = value as DateTime?;
if (dateTimeValue == null)
{
throw new ArgumentOutOfRangeException();
}
string dateTimeString = dateTimeValue?.ToUniversalTime().ToString("o");
DynamoDBEntry entry = new Primitive
{
Value = dateTimeString,
};
return entry;
}
public object FromEntry(DynamoDBEntry entry)
{
Primitive primitive = entry as Primitive;
if (primitive == null || !(primitive.Value is string) || string.IsNullOrEmpty((string)primitive.Value))
{
throw new ArgumentOutOfRangeException();
}
string dateTimeString = primitive.Value as string;
DateTime dateTimeValue = DateTime.Parse(dateTimeString).ToUniversalTime();
return dateTimeValue;
}
}
Few things to note here:
We're calling ToString with "o" to get the round-trip format
We force to UniversalTime before we call ToString("o"); to get the "Z" format of the string instead of the offset format no matter if you pass a DateTimeKind.Local or DateTimeKind.Utc in.
We force to UniversalTime in FromEntry as well, since you seemed to want to use Utc. When comparing DateTime, it's always worth comparing .Kind as well.
We still add this to our context, as in the GitHub example:
context.ConverterCache.Add(typeof(DateTime), new CustomDateTimeConverter());
Note the impact that setting the output DateTimeKind has via this example:
var utcDate = DateTime.UtcNow;
// Create a book.
DimensionType myBookDimensions = new DimensionType()
{
Length = 8M,
Height = 11M,
Thickness = 0.5M,
};
Book utcBook = new Book
{
Id = 501,
Title = "UtcBook",
Isbn = "999-9999999999",
BookAuthors = new List<string> { "Author 1", "Author 2" },
Dimensions = myBookDimensions,
publishedOn = utcDate,
};
var localDate = DateTime.Now;
Book localBook = new Book
{
Id = 502,
Title = "Local Book",
Isbn = "999-1111",
BookAuthors = new List<string> { "Author 1", "Author 2" },
Dimensions = myBookDimensions,
publishedOn = localDate,
};
// Add the book to the DynamoDB table ProductCatalog.
await context.SaveAsync(utcBook);
await context.SaveAsync(localBook);
// Retrieve the book.
Book utcBookRetrieved = await context.LoadAsync<Book>(501);
Console.WriteLine(#$"Original: {utcDate.TimeOfDay}({utcDate.Kind}) => Saved: {
utcBookRetrieved.publishedOn.TimeOfDay}({utcBookRetrieved.publishedOn.Kind}). Equal? {
utcDate.TimeOfDay == utcBookRetrieved.publishedOn.TimeOfDay} ToUniversal() Equal? {
utcDate.ToUniversalTime().TimeOfDay == utcBookRetrieved.publishedOn.ToUniversalTime().TimeOfDay}");
Book localBookRetrieved = await context.LoadAsync<Book>(502);
Console.WriteLine(#$"Original: {localDate.TimeOfDay}({localDate.Kind}) => Saved: {
localBookRetrieved.publishedOn.TimeOfDay}({localBookRetrieved.publishedOn.Kind}). Equal? {
localDate.TimeOfDay == localBookRetrieved.publishedOn.TimeOfDay} ToUniversal() Equal? {
localDate.ToUniversalTime().TimeOfDay == localBookRetrieved.publishedOn.ToUniversalTime().TimeOfDay}");
This prints:
Original: 20:12:52.4810270(Utc) => Saved: 20:12:52.4810270(Utc). Equal? True ToUniversal() Equal? True
Original: 15:12:52.4812120(Local) => Saved: 20:12:52.4812120(Utc). Equal? False ToUniversal() Equal? True
You can also use this method to export ticks, instead. Just change the ToEntry/FromEntry to convert to the number ticks.
First I should mention that I know there are several questions similar to mine, but none of them could help me.
I want to compare two dates which are in two different SQL table and I'm using Lambda Expression.
My code:
var itemStartDate = new ItemsBusiness().GetList<Item>(i => Convert.ToInt64(i.StartDate.Replace("/", "")) < Convert.ToInt64(tdpStartDate.Text.Replace("/", "")));
However when I run the program, this exception shows up:
Input string was not in a correct format. When converting a string to DateTime, parse the string to take the date before putting each variable into the DateTime object.
The line which catches the exception is in another form:
try
{
int inputVal = Convert.ToInt32(value.Trim().Replace("px", ""));
myLabelWidth = inputVal.ToString();
}
p.s: My dates format is like this: "2010/06/20"
This is what I think is happening. I assume that you turn your date into a string like this:
var StartDate = DateTime.Now.Date.ToString();
var tdpStartDate = DateTime.Now.Date.ToString();
var result = Convert.ToInt64(StartDate.Replace("/", "")) < Convert.ToInt64(tdpStartDate.Replace("/", ""));
This will fail with the error you got because the Date is in a format with letters when representing the month.
What you can do is simply to format the Date to include nothing but digits:
var StartDate = DateTime.Now.Date.ToString("ddMMyyyy");
var tdpStartDate = DateTime.Now.Date.ToString("ddMMyyyy");
var result = Convert.ToInt64(StartDate) < Convert.ToInt64(tdpStartDate);
This does not throw the exception like before
How to sort this?
I have List of string with values like this
11-03-2013
11-03-2013 -Count=2
11-03-2013 -count=1
11-04-2013 -Count=1
11-04-2013 -Count=2
11-04-2013
Output should be, The one without the count should be on the last and the top most should be 1 followed by 1 and dates should be ordered by ascending.
11-03-2013 -Count=2
11-03-2013 -count=1
11-03-2013
11-04-2013 -Count=2
11-04-2013 -Count=1
11-04-2013
I tried this code but this is sorting this by descending
var edates= edates.OrderBy(e => e.Replace("-count=1", string.Empty).Replace("-count=2", string.Empty)).ToList();
I know that a simple class with properties can do the trick but doing that so would need to change other methods which would require a lot of work.
Regards
it is because you compare strings not dates. Create two functions: first substrings date part and parses it and second substrings the count part and returns parsed count(or 0 if length < 11) and then yourList.OrderBy(s=> f1(s)).ThenByDescending(s=> f2(s))
Here is #Guru Stron's solution in code
private static void sortList()
{
var dates = getDates();
var sorted = dates.OrderBy(f1).ThenByDescending(f2);
}
private static DateTime f1(string parse)
{
return DateTime.Parse(parse.Substring(0, 10));
}
private static int f2(string parse)
{
int sort;
if (parse.Length > 10) int.TryParse(parse.Substring(18), out sort);
else sort = 0;
return sort;
}
You first need to order by the date, then by the rest of the string, descending;
edates =
edates.OrderBy(x =>
DateTime.ParseExact(x.Substring(0, 10), "MM-dd-yyyy",
CultureInfo.InvariantCulture))
.ThenByDescending(x => x.Substring(10))
.ToList();
You ought to use a real class to simplify things and have a proper representation. That said, you can use the LINQ query syntax and take advantage of the let clause to store the result of splitting the text on a space and the equal symbol. If the split result has more than one element we can assume the count exists. Next, we order by the date (after parsing it) and then by parsing the count (descending).
Try this approach out:
string[] inputs =
{
"11-03-2013",
"11-03-2013 -Count=2",
"11-03-2013 -Count=1",
"11-04-2013 -Count=1",
"11-04-2013 -Count=2",
"11-04-2013"
};
var query = from input in inputs
let split = input.Split(' ', '=')
let count = split.Length > 1 ? int.Parse(split[2]) : 0
orderby DateTime.Parse(split[0]), count descending
select input;
foreach (var item in query)
{
Console.WriteLine(item);
}
The following should order as desired across different years and counts >= 10.
This won't be the "fastest" method (and it will most certainly not work with L2S/EF LINQ providers), but it should sort the given format correctly and fail-fast on invalid values. I would likely write the code like this (or use an IComparer with an equivalent setup) - mainly because it "reads simple" to me.
DateTime OrderableItem (string e) {
var date = e.Substring(0, 10);
return DateTime.ParseExact(date, "MM-dd-yyyy", CultureInfo.InvariantCulture)
}
int OrderableCount (string e) {
var m = Regex.Match(e, #"-count=(\d+)$", RegexOptions.IgnoreCase);
return m.Success
? int.Parse(m.Groups[1].Value)
: 0;
}
var res = seq.OrderBy(OrderableDate)
.ThenBy(OrderableCount);
I much prefer to take data, instead of excluding data.
I am trying to sort my arraylist.
The array list consists of data in time format.
Array:
9:15 AM, 10:20 AM
How should I sort it?
The result i get from below code is :
10:20 AM
9:15 AM
Below is my code:
String timeText = readFileTime.ReadLine();
timeSplit = timeText.Split(new char[] { '^' });
Array.Sort(timeSplit);
foreach (var sortedArray in timeSplit)
{
sortedTimeListBox.Items.Add(sortedArray);
}
Yes, since you simply split a string, you're merely sorting an array of strings (meaning 1 comes before 9 and it doesn't care about the decimal point). To get the sorting you desire, you need to first convert it into a DateTime like this:
timeSplit = timeText
.Split(new char[] { '^' });
.Select(x => new { Time = DateTime.Parse(x), String = x })
.OrderBy(x => x.Time)
.Select(x => x.String)
.ToArray();
Here, what we've done is:
Split the string as you had done before
Create a new anonymous type that contains the original string and also that string converted into a DateTime.
Ordered it by the DateTime property
Select'ed back to the original string
Converted it into an array
timeSplit now contains the strings sorted as you wanted.
Array.Sort(timeSplit, delegate(string first, string second)
{
return DateTime.Compare(Convert.ToDateTime(first), Convert.ToDateTime(second));
});
I need to compare two files based on datetime. I need to check whether these two files were created or modified with same datetime. I have used this code to read the datetime of files...
string fileName = txtfile1.Text;
var ftime = File.GetLastWriteTime(fileName).ToString();
string fileName2 = txtfile2.Text;
var ftime2 = File.GetLastWriteTime(fileName2).ToString();
Any suggestions?
Don't call ToString() on the DateTime values returned by GetLastWriteTime(). Do this instead:
DateTime ftime = File.GetLastWriteTime(fileName);
DateTime ftime2 = File.GetLastWriteTime(fileName2);
Then you can just compare ftime and ftime2:
if (ftime == ftime2)
{
// Files were created or modified at the same time
}
Well, how about doing
ftime == ftime2
? No need for the ToString though, better just compare DateTimes as-is.
The precision of the last modification time being stored in a file system varies between different file systems (VFAT, FAT, NTFS). So, its best to use an epsillon environment for this and either let the user choose a sensible value or choose a value based on the involved file systems.
https://superuser.com/questions/937380/get-creation-time-of-file-in-milliseconds
double epsillon = 2.0
DateTime lastUpdateA = File.GetLastWriteTime(filename);
DateTime lastUpdateB = File.GetLastWriteTime(filename2);
if (Math.Abs(Math.Round((lastUpdateA - lastUpdateB).TotalSeconds)) > epsillon)
different = true;
GetLastWriteTime() returns a DateTime object, so you can do this:
if (File.GetLastWriteTime(filename).CompareTo(File.GetLastWriteTime(filename2)) == 0)
to test if they have the same timestamp.
See this for more tips on comparing DateTime objects.
bool isMatched=false;
int ia = string.Compare(ftime.ToString(), ftime2.ToString());
if (string.Compare(ftime.ToString(), ftime.ToString()) == 0)
isMatched = true;
else
isMatched = false;