I have two arrays, UserActivity and UserDateTime. User Activity array holds the activities of what the user is doing and the UserDateTime holds the DateTime of the said activity. I cannot find a solution where I can output the DateTime where it's greater than such Date/Time whilst printing out the user activity.
For example:
[UserDateTime] [UserActivity]
02/02/2018 02:20 User logs on
05/02/2018 15:20 User visits page
20/02/2018 16:10 User goes here
21/02/2018 12:00 User logs off
21/02/2018 13:00 User logs on
21/02/2018 15:00 User visits here
The Date and time has its own array (UserDateTime) while the users' activity is in the array UserActivity'.
etc.
My problem is that I can't programmatically output where the DateTime is greater than 20/02/2019 and the User Activity is linked to the date/time.
My code is followed:
string[] UserActivity = File.ReadAllLines(#"useractivityfile");
string[] UserDateTime = File.ReadAllLines(#"userdatetimesfile");
DateTime greaterthanthis = new DateTime(2018, 2, 20);
for (int i = 0; i < UserActivity.Length; i++)
{
if (DateTime.ParseExact(UserDT[i], "dd/MM/yyyy", CultureInfo.InvariantCulture) > greaterthanthis)
{
Console.WriteLine(UserDT[i].Where(x >= greaterthanthis????); //very stuck on this part
//Also want to link the useractivity so Console.WriteLine(UserDT[i] + UserDT[i])
}
}
I've been overthinking and overcomplicating this code all week (stressed). Thank you for your help.
Try this pls. The format of the string representation must match a specified format exactly or an exception is thrown.
string[] UserActivity = File.ReadAllLines(#"path");
string[] UserDateTime = File.ReadAllLines(#"path");
DateTime greaterthanthis = new DateTime(2018, 2, 20);
for (int i = 0; i < UserActivity.Length; i++)
{
if (DateTime.ParseExact(UserDateTime[i], "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture) > greaterthanthis)
{
Console.WriteLine(UserDateTime[i].ToString() + " : " + UserActivity[i]);
}
}
There is plenty of typo in your code:
for (int i = 0; x < UserActivity.Length; i++)
=> for (int i = 0; i < UserActivity.Length; i++)
if (DateTime.ParseExact(UserDT[i], "dd/MM/yyyy", CultureInfo.InvariantCulture > greaterthanthis ) )
=> if (DateTime.ParseExact(UserDT[i], "dd/MM/yyyy", CultureInfo.InvariantCulture ) > greaterthanthis)
The ParseExact format match your 1rst version but doesn't match your file format
The easier step will be to get away from those files and make a reasonable object out of it:
public class Logs
{
public DateTime Date { get; set; }
public string Name { get; set; }
public string Activity { get; set; }
}
Note that you example bothe file don't have the same number of lines...
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
public class Logs
{
public DateTime Date { get; set; }
public string Name { get; set; }
public string Activity { get; set; }
}
public static void Main(string[] args)
{
var UserDateTime_TEXT = #"02/02/2018 02:20
05/02/2018 15:20
21/02/2018 12:00
21/02/2018 13:00
21/02/2018 15:00 ";
var UserActivity_TEXT = #"User logs on
User visits page
User goes here
User logs off
User logs on
User visits here";
//Equivalent to ReadAllLines
string[] UserDateTime = UserDateTime_TEXT.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
string[] UserActivity = UserActivity_TEXT.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
// ps in your exemple there is more activity than date time...
// UserDateTime.Length != UserActivity.Length !!!!!!!!!!!
var data = new List<Logs>();
//in your code you had `x < UserActivity.Length`, what is x?
for (int i = 0; i < UserDateTime.Length; i++)
{
var splitValues = UserActivity[i].Split(' ');
var temp =
new Logs
{
Date = DateTime.ParseExact(UserDateTime[i].Trim(), "dd/MM/yyyy HH:mm", CultureInfo.InvariantCulture),
Name = splitValues[0], // No space in username.
Activity = string.Join(" ", splitValues.Skip(1))
};
data.Add(temp);
}
//filter
var greaterThanThis = new DateTime(2018, 2, 20);
var result = data.Where(x=> x.Date > greaterThanThis);
foreach(var entry in data){
Console.WriteLine($"{entry.Name} did {entry.Activity} at {entry.Date}");
}
}
Live Demo
Frankly speaking, your code looks like a complete mess. Brackets were wrong, variable names were wrong, LINQ query was wrong as well.
Use this as a start:
string[] UserActivity = File.ReadAllLines(#"useractivityfile");
string[] UserDateTime = File.ReadAllLines(#"userdatetimesfile");
DateTime greaterthanthis = new DateTime(2019, 1, 12);
for (int i = 0; i < UserActivity.Length; i++)
{
if (DateTime.ParseExact(UserDateTime[i], "dd/MM/yyyy", CultureInfo.InvariantCulture) > greaterthanthis)
{
Console.WriteLine(UserDateTime[i]);
//Also want to link the useractivity so Console.WriteLine(UserDT[i] + UserDT[i])
}
}
If you want a LINQ query, try this:
UserDateTime.Where(x => DateTime.ParseExact(x, "dd/MM/yyyy", CultureInfo.InvariantCulture) > greaterthanthis).ToList().ForEach(dt => Console.WriteLine(dt));
But I recommend to stay with the upper code for an easier overview and debugging.
Related
I have a string variable that holds the value of "02/04/2018 to 08/04/2018".
string dateRange = "02/04/2018 to 08/04/2018";
I have a function in c# that gets all the date within the range of 02/04/2018 to 08/04/2018 as per below.
public string getDateRange(string dateRange) {
var selectedDates = new List<DateTime?>();
for (var date = Convert.ToDateTime("02/04/2018");
date <= Convert.ToDateTime("08/04/2018");
date = date.AddDays(1)) {
selectedDates.Add(date);
}
foreach (var date in selectedDates) {
Console.WriteLine(date);
}
return selectedDates;
}
What I want to achieve in this method is to remove the word to in the date range and pass the starting date and ending date separately. Can someone please help ?
You can use String.Split() to separate the dates:
public string[] separateDates(string dateRange)
{
string[] dateSplit = dateRange.Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries);
return new string[]{dateSplit[0].Trim(), dateSplit[1].Trim()};
}
The method returns a string array that holds the first ("02/04/2018") and the second date ("08/04/2018"):
static void Main()
{
string dateRange = "02/04/2018 to 08/04/2018";
string[] myDates = separateDates(dateRange);
string firstDate = myDates[0];//"02/04/2018"
string secondDate = myDates[1];//"08/04/2018"
}
EDIT:
I have implemented my method that separates the dates into your method:
public List<DateTime?> getDateRange(string dateRange)
{
var selectedDates = new List<DateTime?>();
string[] dateSplit = dateRange.Split(new string[] { "to" }, StringSplitOptions.RemoveEmptyEntries);
for (var date = Convert.ToDateTime(dateSplit[0].Trim());
date <= Convert.ToDateTime(dateSplit[1].Trim());
date = date.AddDays(1))
{
selectedDates.Add(date);
}
foreach (var date in selectedDates)
{
Console.WriteLine(date.Value.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
return selectedDates;
}
The method now returns List<DateTime?> instead of string because the type of selectedDates is List<DateTime?>. I also made a modification to the console output, now the dates are printing to the console in the following format dd/MM/yyyy (e.g. 02/04/2018).
LastIndexOf: This method searches strings from the right. It finds the location of the last occurrence of a letter or substring. It is the reversed version of IndexOf.
public static void Main(string[] args)
{
string str = "02/04/2018 to 08/04/2018";
int pos = str.LastIndexOf("to");
string result = str.Substring(0, pos) + " " + str.Substring(pos + 2);
Console.WriteLine(result);
}
Fiddle
Its printing the date as : 02.04.2018 00:00:00. I have specified the string to dd/MM/yyyy. It just removes the 00:00:00 but keeps the dot in between.
Here is the little amendment to fix that:
Console.WriteLine(date.Value.ToString("dd/MM/yyyy"));
private void CreateCountryDateTimeDirectories(List<string> urls)
{
//48
// 12
for (int i = 0; i < urls.Count(); i++)
{
string pathDateTime = urls[i].Substring(48, 12);
}
}
First iteration for example in pathDateTime:
201701122100 if i will split it to date and time: year 2017 month 01 day 12 hours 21 minutes 00
So i want to format it some how in a string to my local time format in this case Israel. Not to change it to my local time but to format it as date time like it's formatting in my country.
And then to format also the last item:
201701122300
After formatting both the first and last items i want to create a directory on the hard disk in this format:
This is example of the date and time in Israel and this is how i want the directory to be created:
[12-01-2017_21:00---12-01-2017_2300]
Or maybe some other format maybe something nicer ? But the idea is to create a directory of the date and time range.
private void CreateCountryDateTimeDirectories(List<string> urls)
{
//48
// 12
var lowDate = null;
var highDate = null;
var thisDate = null;
for (int i = 0; i < urls.Count(); i++)
{
string pathDateTime = urls[i].Substring(48, 12);
thisDate = DateTime.ParseExact(pathDateTime, "yyyyMMddHHmm", CultureInfo.InvariantCulture;
if (lowDate == null) lowDate = thisDate;
if (highDate == null) highDate = thisDate;
if (thisDate < lowDate) lowDate = thisDate;
if (thisDate > highDate) highDate = thisDate;
}
System.IO.Directory.CreateDirectory($"{lowDate.ToString("MM-dd-yyyy_HH:mm")}---{highDate.ToString("MM-dd-yyyy_HH:mm")});
}
Keep coding!
how do I used date on searching using Linq. I think I'm missing something on the declaration
string searchName = Request.Form["PersonName"];
DateTime searchDateFrom = Request.Form["ReceivedDateFrom"];
DateTime searchDateTo = Request.Form["ReceivedDateTo"];
var Results = (from va in _db.myTable
where ((va.PersonName.Contains(searchName)
&& (va.ApplicationReceivedDate > searchDateFrom
&& va.ApplicationReceivedDate < searchDateTo)
select va).ToList();
HttpRequest.Form is a NameValueCollection, where you can get strings in it by int/string indexer. That is, Request.Form["ReceivedDateFrom"] returns a string, you can't assign it to a variable whose type is DateTime without any convert. You can try DateTime.ParseExact method to convert the string to a DateTime. But if you can't guarantee the string has a correct format, you can use a TryParse method.
Might be a typo, but you need to cast searchDateFrom / searchDateTo to a DateTime and you have two extra open brackets in your linq statement
I'd also recommand using a cleaner indentation, it's easier to follow and count the brackets and stuff.
string searchName = Request.Form["PersonName"];
DateTime searchDateFrom = Request.Form["ReceivedDateFrom"];
DateTime searchDateTo = Request.Form["ReceivedDateTo"];
var Results = (from va in _db.myTable
where va.PersonName.Contains(searchName)
&& (va.ApplicationReceivedDate > searchDateFrom
&& va.ApplicationReceivedDate < searchDateTo)
select va).ToList();
This is when I setup a unit test to see what's going on.
Check your brackets and casting from string to datetime:
[TestMethod]
public void TestMethod1()
{
List<myTable> myTables = new List<myTable>();
for (int month = 1; month < 10; month++)
{
for (int day = 1; day < 20; day++)
{
myTables.Add(new myTable { PersonName = "Person " + month.ToString() + " " + day.ToString(), ApplicationReceivedDate = new DateTime(2011, month, day) });
}
}
string searchName = "Person";
DateTime searchDateFrom = Convert.ToDateTime("2011-01-02");
DateTime searchDateTo = Convert.ToDateTime("2011-01-03");
var Results = (from va in myTables
where va.PersonName.Contains(searchName)
&& va.ApplicationReceivedDate >= searchDateFrom
&& va.ApplicationReceivedDate < searchDateTo
select va);
Assert.AreEqual(Results.Count(), 1);
}
public class myTable
{
public string PersonName { get; set; }
public DateTime ApplicationReceivedDate { get; set; }
}
Also check the search from & to.
I have a date and I need to populate a drop-down with the months/years between that date and today. For instance, if that date is 10/14/2010 then the drop-down should contain October 2010, November 2010, December 2010, January 2011.
The way I'm thinking of doing this is to pass that date to a function, loop from today backwards step 1 month while adding each month to a collection until we reach that date and finally return a collection of strings. Then, populate the drop-down control on page load. Finally, use some ajax with a page method to parse back the string and trigger a partial page reload.
I'm just wondering if there's an easy way to do it.
Thanks.
Maybe you can try this:
static IEnumerable<DateTime> monthsBetween(DateTime startDate, DateTime endDate)
{
return Enumerable.Range(0, (endDate.Year - startDate.Year) * 12 + (endDate.Month - startDate.Month + 1))
.Select(m => new DateTime(startDate.Year, startDate.Month, 1).AddMonths(m));
}
This will not give you the result in the exact format that you want, but you get the drift. :)
You can do something like this which is pretty much what you described except counting forward:
private string[] FillDropDownWithDates(DateTime dt)
{
DateTime dtnow = DateTime.Now;
List<string> values = new List<string>();
if ( (dt <= dtnow))
{
values.Add(String.Format("{0:y}", dt));
}
while ( (dt = dt.AddMonths(1)) <= dtnow || ( dt.Month == dtnow.Month && dt.Year == dtnow.Year) )
{
values.Add(String.Format("{0:y}", dt)); // "March, 2008" YearMonth
}
return values.ToArray();
}
public static List<string> GetMonths(DateTime StartDate)
{
List<string> MonthList = new List<string>();
DateTime ThisMonth = DateTime.Now.Date;
while (ThisMonth.Date > StartDate.Date)
{
MonthList.Add(ThisMonth.ToString("MMMM") + " " + ThisMonth.Year.ToString());
ThisMonth = ThisMonth.AddMonths(-1);
}
return MonthList;
}
For Year,
public static IEnumerable<int> Range (int start, int count)
{
int end = start + count;
for (int i = start; i < end; i++)
yield return i;
}
var startYear = 2000;
YearDropDownList.ItemsSource= Enumerable.Range(startYear, 2050 - startYear + 1);
For Month,
An enumerable list with .ToString("MMMM") format.
This is how I got a 12 month/year. Hope the code helps.
public IEnumerable<SelectListItem> Additional12Months {
get
{
return Enumerable.Range(12, 12).Select(i => new SelectListItem { Value = DateTime.Now.AddMonths(-(i)).ToShortDateString(), Text = DateTime.Now.AddMonths(-(i)).ToString("MMM-yyyy") }).ToList();
}
}
I have this : Datetime.Now(); or 23/10/2009
I want this : Friday
For local date-time (GMT-5) and using Gregorian calendar.
//default locale
System.DateTime.Now.DayOfWeek.ToString();
//localized version
System.DateTime.Now.ToString("dddd");
To make the answer more complete:
DayOfWeek MSDN article
If localization is important, you should use the "dddd" string format as Fredrik pointed out - MSDN "dddd" format article
If you want to know the day of the week for your code to do something with it, DateTime.Now.DayOfWeek will do the job.
If you want to display the day of week to the user, DateTime.Now.ToString("dddd") will give you the localized day name, according to the current culture (MSDN info on the "dddd" format string).
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(System.DateTime.Now.DayOfWeek)
or
System.Threading.Thread.CurrentThread.CurrentUICulture.DateTimeFormat.GetDayName(DateTime.Parse("23/10/2009").DayOfWeek)
DateTime.Now.DayOfWeek quite easy to guess actually.
for any given date:
DateTime dt = //....
DayOfWeek dow = dt.DayOfWeek; //enum
string str = dow.ToString(); //string
Here is more simple
DateTime dt;
string yourdate = dt.DayOfWeek.ToString()
better than declare redundant DayOfWeek
DateTime now = DateTime.Now
string s = now.DayOfWeek.ToString();
try this:
DateTime.Now.DayOfWeek
You're looking for the DayOfWeek property.
Here's the msdn article.
What about if we use String.Format here
DateTime today = DateTime.Today;
String.Format("{0:dd-MM}, {1:dddd}", today, today) //In dd-MM format
String.Format("{0:MM-dd}, {1:dddd}", today, today) //In MM-dd format
(DateTime.Parse((Eval("date").ToString()))).DayOfWeek.ToString()
at the place of Eval("date"),you can use any date...get name of day
I use this Extension Method:
public static string GetDayName(this DateTime date)
{
string _ret = string.Empty; //Only for .NET Framework 4++
var culture = new System.Globalization.CultureInfo("es-419"); //<- 'es-419' = Spanish (Latin America), 'en-US' = English (United States)
_ret = culture.DateTimeFormat.GetDayName(date.DayOfWeek); //<- Get the Name
_ret = culture.TextInfo.ToTitleCase(_ret.ToLower()); //<- Convert to Capital title
return _ret;
}
Random Rnd = new Random();
RandomDates Rdate = new RandomDates();
PaymentDetails Payd = new PaymentDetails();
DayOfWeek strDay = DateTime.Today.DayOfWeek;
var dateTime = DateTime.Now;
var dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
StepDescription = "Fill MatterInformation. ";
Console.Write(" Input the Day : ");
dt = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Month : ");
mn = Convert.ToInt32(Console.ReadLine());
Console.Write(" Input the Year : ");
yr = Convert.ToInt32(Console.ReadLine());
DateTime d = new DateTime(2021, 04, yr);
var culture = System.Threading.Thread.CurrentThread.CurrentCulture;
var diff = d.DayOfWeek - culture.DateTimeFormat.FirstDayOfWeek;
if (diff < 0)
diff += 7;
var x = d.AddDays(-diff).Date;
dateTime = DateTime.Now;
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
Console.WriteLine($"Date Value: {dateValue2}");
// strDay =
}
if (!strDay.Equals("Sunday") | !strDay.Equals("Saturday"))
{
Console.WriteLine("___________________OK____________________________________________");
// string NotificateionDate = Rdate.DateWithin_PastDays(Rnd.Next(30, 260)).ToString(#"MM\/dd\/yyyy");
// CustomLibrary.seWaitUntilElementIsVisible(10, NotiFiedDateTab.Actions.seGetLocator(), "NotiFiedDateTab");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
else
{
Console.WriteLine("_________________________NOT______________________________________");
if (strDay.Equals("Sunday"))
{
dateTime = dateTime.AddDays(-2);
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
else if (strDay.Equals("Saturday"))
{
dateTime = dateTime.AddDays(-1);
dateValue2 = dateTime.ToString(#"MM\/dd\/yyyy");
NotiFiedDateTab.Actions.Set(ControlPropertyNames.Text, dateValue2);
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessTheDay
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter the Day Number ");
int day = int.Parse(Console.ReadLine());
Console.WriteLine(" Enter The Month");
int month = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Year ");
int year = int.Parse(Console.ReadLine());
DateTime mydate = new DateTime(year,month,day);
string formatteddate = string.Format("{0:dddd}", mydate);
Console.WriteLine("The day should be " + formatteddate);
}
}
}