Convert string into datetime in razor view with javascript? - c#

In my controller I convert the datetime into string
here's the code
var result = from c in displayedCustomers select new[] { c.NonActiveDate.ToString("dd-MM-yyyy HH:mm:ss")};
and I want to convert it back to datetime cause I want to compare it with today date
this is my code and not working cause the string cannot be compare with date
if (d <= Date.now)
{
return '<span style = "color : red">' + oObj.aData[4]+ '</span>';
}

Convert your string to Date object in java script using "Date" function before comparing
if(new Date("your date string") <= Date.now)
{
// your code
}

cant you fill another string with the date time now and compare them that way.
{
var time = DateTime.Now;
string Time = time.ToString();
if(yourtimevariable == Time)
{
//enter what you want to do when the if statement is true
}
}

Related

C# Date in CSV file

I have to change a csv file with several dates in it. Every row starts with a date followed whith data.
11-nov-2015,data,data,data
10-nov-2015,data,data,data
9-nov-2015,data,data,data
With the following code I put the data in the right place (20141109 (yyyymmdd))
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
string[] parts = values[0].Split('-');
if (parts.Length == 3)
{
values[0] = String.Format("{0}-{1}-{2}", parts[2], parts[1], parts[0]);
lines1[i] = String.Join(",", values);
}
}
But two problems remain:
1) The month has to change from nov to 11
2) In the file I download the day for example 9-nov-2014 has to change to 09. for 8-nov-2014 to 08. So an extra 0.
How can this be solved in C#
Instead of making your own datetime format parser, you should use the one already available for you. DateTime.TryParseExact is your tool to convert a string in a date when you know the exact format.
Converting back the date, in the string format that you like, is another task easily solved by the override of ToString() specific for a datetime
string[] values = lines1[i].Split(',');
if (values.Length >= 3)
{
DateTime dt;
if (DateTime.TryParseExact(values[0], "d-MMM-yyyy",
System.Globalization.CultureInfo.CurrentCulture,
System.Globalization.DateTimeStyles.None, out dt))
{
values[0] = dt.ToString("yyyyMMdd");
lines1[i] = String.Join(",", values);
}
}
I would parse the string into a date and then write it back using a custom date format. From this link we can write this code:
String pattern = "dd-MMM-yyyy";
DateTime dt;
if (DateTime.TryParseExact(values[0], pattern, CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt)) {
// dt is the parsed value
String sdt = dt.ToString("yyyyMMdd"); // <<--this is the string you want
} else {
// Invalid string, handle it as you see fit
}

How to compare two persian date to find out which one is greater?

I want to compare two persian dates to find out which one is greater, I use this function :
public static List<MatchDrawHistory> GetAllMatchDrawHistory(string startDate, string endDate)
{
using (var db= new ReceiveSendEntitiesV5())
{
var matchDrawList = db.MatchDrawHistories.Where(x => String.CompareOrdinal(x.DrawStartDate,startDate)>=0 && String.CompareOrdinal(x.DrawEndDate , endDate) <=0).ToList();
return matchDrawList;
}
}
but it does not work, how can I do it?
EDIT: DrawStartDate and DrawStartDate are nvarchar(20) in DataBase, and these are persian date not gregorian date
First you need to convert your string date to DateTime. Assuming your string date is as yyyy/MM/dd, the conversion function can be as follow:
private static DateTime ParseDate(string date)
{
var pc = new PersianCalendar();
string[] arrDate = date.Split("/");
return pc.ToDateTime(Int32.Parse(arrDate[0]), Int32.Parse(arrDate[1]),
Int32.Parse(arrDate[2]), 0, 0, 0, 0);
}
Now you can use the following method to compare two dates:
private static bool Compare(DateTime firstDate, DateTime secondDate)
{
return firstDate >= secondDate;
}
Your problem is that you're trying to store the dates as strings. I presume the dates in your class are strings, so I would pass in a DateTime, and use something like the following:
var matchDrawList = db.MatchDrawHistories.Where(x => DateTime.Parse(x.DrawStartDate) >= startDate && DateTime.Parse(x.DrawEndDate) <= endDate).ToList();
If you're not sure that the string will resolve to a date correctly, you could create a function to wrap a TryParse, depending on your business logic this may be preferable, as presumably you still want other results if one has an invalid date.
static bool CheckDateGreater(string date1, string date2)
{
DateTime dt1;
if (!DateTime.TryParse(date1, out dt) return false;
DateTime dt2;
if (!DateTime.TryParse(date2, out dt) return false;
return (dt1 >= dt2);
}
Then call:
var matchDrawList = db.MatchDrawHistories.Where(x => CheckDateGreater(x.DrawStartDate, startDate) && CheckDateGreater(endDate, x.DrawEndDate).ToList();
EDIT:
Just seen your comment about Persian date. You need to use the PersianCalendar class. That should return you a DateTime object.
Use DateTime for the comparison rather than string
var start = DateTime.Parse(startDate);
var end = DateTime.Parse(endDate);
...
db.MatchDrawHistories.Where(x => x.DrawStartDate >= start && x.DrawEndDate <= end)
Use CompareTo method like below code:
if(endDate.CompareTo(startDate) < 0)
//startDate is greater

How to check the date format in given structure

I have passing a date in query string as the format of 02-2014.and using this date I done the search.It is working and the result is perfect .but when I change the query string value in the browser then the error will showing.In this condition I need only some message,So how can we check the query string date value is in correct format.my code is
string dateToSearch = HttpContext.Current.Request["date"];
if (!string.IsNullOrEmpty(dateToSearch))
{
dateToSearch = dateToSearch.Trim();
string year = null;
string month = null;
var dates = dateToSearch.Split("-".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
if (dates.Length > 0)
{
month = dates[0];
year = dates[1];
}
}
Just use DateTime.TryParseExact with the format string MM-yyyy. This will tell you whether your input string is in the format you specified and if so, it returns the parsed DateTime object via an out parameter.
Try this:
DateTime date;
if (DateTime.TryParseExact(text, "MM'-'yyyy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
// Success
}
else
{
// Parse failed
}

How to Format a date pass as a parameter to a function and return data is a string with "yyyy/mm/dd" format?

How to Format a date pass as a parameter to a function and return data is a string with "yyyy/mm/dd" format ?
for example if I would want to format a string retrieved from textbox and I want a special function to format it and return as a string format.
string myDate = txtJoiningDate.Text,
my function should be :
public string GetFormattedDate(string myDate)
{
//Formating should happen here.
return myDate;
}
public string GetFormattedDate(String MyDateTime)
{
//Formating should happen here.
DateTime dt = DateTime.Parse(MyDateTime);
return dt.ToString("yyyy/MM/dd");
}
also can be done with this
string dt = DateTime.Parse(txtDate.Text.Trim()).ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);
you need to parse the string to a DateTime object however you need to make sure that the format you are going to parse will work.
take a look at DateTime.Parse (or TryParse):
http://msdn.microsoft.com/en-us/library/1k1skd40.aspx
then you simply do:
// lets say you are creating your datetime:
DateTime dt = new DateTime(2013, 11, 1);
return dt.ToString("dd/MM/yyyy");
the above will return 01/11/2013
more information:
http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
Hurrey.I got the answer.Working 100%. Hope will be helpful for others.
public string FormatPostingDate(object obj)
{
if (obj != null && obj.ToString() != string.Empty)
{
DateTime postingDate = Convert.ToDateTime(obj);
return string.Format("{0:yyyy/MM/dd}", postingDate);
}
return string.Empty;
}
also can be done with this
using System.Globalization;
string dt = DateTime.Parse(txtDate.Text.Trim()).ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

Is there a way to compare two DateTime variables in Linq2Sql but to disregard the Time part.
The app stores items in the DB and adds a published date. I want to keep the exact time but still be able to pull by the date itself.
I want to compare 12/3/89 12:43:34 and 12/3/89 11:22:12 and have it disregard the actual time of day so both of these are considered the same.
I guess I can set all the times of day to 00:00:00 before I compare but I actually do want to know the time of day I just also want to be able to compare by date only.
I found some code that has the same issue and they compare the year, month and day separately. Is there a better way to do this?
try using the Date property on the DateTime Object...
if(dtOne.Date == dtTwo.Date)
....
For a true comparison, you can use:
dateTime1.Date.CompareTo(dateTime2.Date);
This is how I do this in order to work with LINQ.
DateTime date_time_to_compare = DateTime.Now;
//Compare only date parts
context.YourObject.FirstOrDefault(r =>
EntityFunctions.TruncateTime(r.date) == EntityFunctions.TruncateTime(date_to_compare));
If you only use dtOne.Date == dtTwo.Date it wont work with LINQ (Error: The specified type member 'Date' is not supported in LINQ to Entities)
If you're using Entity Framework < v6.0, then use EntityFunctions.TruncateTime
If you're using Entity Framework >= v6.0, then use DbFunctions.TruncateTime
Use either (based on your EF version) around any DateTime class property you want to use inside your Linq query
Example
var list = db.Cars.Where(c=> DbFunctions.TruncateTime(c.CreatedDate)
>= DbFunctions.TruncateTime(DateTime.UtcNow));
DateTime dt1 = DateTime.Now.Date;
DateTime dt2 = Convert.ToDateTime(TextBox4.Text.Trim()).Date;
if (dt1 >= dt2)
{
MessageBox.Show("Valid Date");
}
else
{
MessageBox.Show("Invalid Date... Please Give Correct Date....");
}
DateTime? NextChoiceDate = new DateTime();
DateTIme? NextSwitchDate = new DateTime();
if(NextChoiceDate.Value.Date == NextSwitchDate.Value.Date)
{
Console.WriteLine("Equal");
}
You can use this if you are using nullable DateFields.
DateTime dt1=DateTime.ParseExact(date1,"dd-MM-yyyy",null);
DateTime dt2=DateTime.ParseExact(date2,"dd-MM-yyyy",null);
int cmp=dt1.CompareTo(dt2);
if(cmp>0) {
// date1 is greater means date1 is comes after date2
} else if(cmp<0) {
// date2 is greater means date1 is comes after date1
} else {
// date1 is same as date2
}
DateTime econvertedDate = Convert.ToDateTime(end_date);
DateTime sconvertedDate = Convert.ToDateTime(start_date);
TimeSpan age = econvertedDate.Subtract(sconvertedDate);
Int32 diff = Convert.ToInt32(age.TotalDays);
The diff value represents the number of days for the age. If the value is negative the start date falls after the end date. This is a good check.
In .NET 5:
To compare date without time you must use EF.Functions.DateDiffDay() otherwise you will be comparing in code and this means you are probably pulling way more data from the DB than you need to.
.Where(x => EF.Functions.DateDiffDay(x.ReceiptDate, value) == 0);
You can try
if(dtOne.Year == dtTwo.Year && dtOne.Month == dtTwo.Month && dtOne.Day == dtTwo.Day)
....
In your join or where clause, use the Date property of the column. Behind the scenes, this executes a CONVERT(DATE, <expression>) operation. This should allow you to compare dates without the time.
int o1 = date1.IndexOf("-");
int o2 = date1.IndexOf("-",o1 + 1);
string str11 = date1.Substring(0,o1);
string str12 = date1.Substring(o1 + 1, o2 - o1 - 1);
string str13 = date1.Substring(o2 + 1);
int o21 = date2.IndexOf("-");
int o22 = date2.IndexOf("-", o1 + 1);
string str21 = date2.Substring(0, o1);
string str22 = date2.Substring(o1 + 1, o2 - o1 - 1);
string str23 = date2.Substring(o2 + 1);
if (Convert.ToInt32(str11) > Convert.ToInt32(str21))
{
}
else if (Convert.ToInt32(str12) > Convert.ToInt32(str22))
{
}
else if (Convert.ToInt32(str12) == Convert.ToInt32(str22) && Convert.ToInt32(str13) > Convert.ToInt32(str23))
{
}

Categories

Resources