My Question is that, I want to find the highest DateTime from a list of DateTime?
I have one Array suppose string[] btime = new string[100];
In that Array I am storing the Date which is coming from the SQL-Server
The SQL Query is [CONVERT(varchar(10),GETDATE(),101)] it is returning the Date in format of MM/dd/yyyy
and then after I am concatenating the Date with my own given Time
i.e .btime[j] = SqlServerDate + " " + 15:20; and so on;
Now, from this given Array I want to find highest Date and Time
So, I have use this logic
string large=""
large=btime[0];
for (int i = 0; i < j; i++)
{
if (DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
{
large = btime[i];
}
}
but I am getting the Error at
if(DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
The Error is String not recognized as valid DateTime This error is occurring because of my System DateTime Format is yyyy/dd/MM
So Plz any one can help me in solving this problem
I don't want to change format of the system
Others have suggested different ways of parsing the DateTime. This seems pointless to me - if you can possibly change the query, just avoid performing the conversion to a string in the first place. The fewer conversions you use, the fewer chances you have for this sort of thing to be a problem.
Change the query so you end up with DateTime values, and then finding the latest one is trivial in LINQ:
DateTime latest = dateTimes.Max();
Hum,
// Containing your datetime field
string[] btime = new string[100];
var max = btime.Select(s => DateTime.Parse(s, "MM/dd/yyyy", CultureInfo.InvariantCulture)).Max();
Use the DateTime.ParseExact Method.
Example:
CultureProvider provider = CultureInfo.InvariantCulture;
DateTime.ParseExact(btime[i], "yyyy/dd/MM", provider);
you, can use DateTime.ParseExact() functionality to do this. Refer the following code part.
CurDate = DateTime.ParseExact(Name3, "yyyyMMddhhmmssffff", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
You can use the DateTime.ParseExact() method.
CultureProvider provider = CultureInfo.InvariantCulture;
DateTime.ParseExact(btime[i], "MM/dd/yyyy HH:mm", provider);
The second parameter there is the format string. This specifies how your date will be formatted.
Since you are adding a 24 hour time at the end you need the HH:mm (HH says expect a 24 hour time).
Thanks to everyone.
I have got some sort of answer:
string large = "";
large = btime[0];
IFormatProvider culture = System.Threading.Thread.CurrentThread.CurrentCulture;
// This Code will convert the System Format in Thread, Not the Actual Format
// of The System
CultureInfo ciNewFormat = new CultureInfo(CultureInfo.CurrentCulture.ToString());
ciNewFormat.DateTimeFormat.ShortDatePattern = "MM/dd/yyyy";
System.Threading.Thread.CurrentThread.CurrentCulture = ciNewFormat;
for (int i = 0; i < TimeBackupCounter; i++)
{
if (DateTime.Compare(DateTime.Parse(btime[i]),DateTime.Parse(large)) > 0)
{
large = btime[i];
}
}
Related
I have two parameters one for date and another for time, and i need date value part and time values part.
My two parameters are below.
// For Date parameter
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
bo.Dateused5 = dt;
// For Time parameter
string Fromtiming = ddl_FromHours.SelectedItem.ToString() + ":" + ddl_FromMinutes.SelectedItem.ToString();
DateTime InterviewTime = Convert.ToDateTime(Fromtiming);//StartTime
bo.Dateused4 = InterviewTime;//InterviewTime
so i need to send mail to the candidate to only date part, should not contain time and time part, should not contain date.
are you looking for this:
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
string mailDate = dt.ToString("dd-MMM-yyyy");// will give 01-jan-1999
string date = dt.ToString("dd-MM-yyyy"); // will give 01-01-1999
You can also try using String.Format()
string mailDate = String.Format("{0:dd-MM-yyyy}", dt); // will give 01-01-1999
You can use ToShortDateString():
DateTime dt = DateTime.ParseExact("01-jan-1999", "dd-MMM-yyyy", CultureInfo.InvariantCulture);
var date = dt.ToShortDateString();
Note that it uses date format attached to the current thread's culture info.
You would need to use strings rather than dates, so change the type of your variables to string so that
bo.Dateused5 = dt.ToString("dd-MMM-yyyy")
would set Dateused5 to a string of the date component, then
bo.Dateused4 = InterviewTime.ToString("HH:MM");
would set Dateused4 to the time component.
Couldn't test your code but I am very sure there are Functions "DateValue" and "TimeValue" you can make use of.
Something like,
Format(DateValue(any datetime), "dd-MM-yyyy")
gives you Only Date in the specified format. Similar way for TimeValue
I have been going through the motions and still cannot seem to get this right. I have textboxes in a gridview that are populated from an access database. They are all datetime values. In the backend code, I am trying to loop through all those values and then apply conditional formatting. For some unknown reason I am unable to get the value from those textboxes in the gridview and when I do, they are seen by the app as string as opposed to datetime. Converting is futile as the same error, "String was not recognized as a valid DateTime." keeps popping up.
Any ideas on how to get values from a gridview textbox, and then convert them from a string to a datetime format?
Here is the code thus far...
for (int p = 0; p < rowscount; p++)
{
var myLabel2 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label2");
var myLabel4 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label4");
DateTime start = Convert.ToDateTime(myLabel2.Text).Date;
DateTime now = DateTime.Now.Date;
DateTime end = Convert.ToDateTime(myLabel4.Text).Date;
if (now >= start && now <= end)
{
myLabel2.BackColor = Color.Chartreuse;
myLabel4.BackColor = Color.Chartreuse;
myLabel7.BackColor = Color.Chartreuse;
myLabel9.BackColor = Color.Chartreuse;
}
else
{
myLabel2.BackColor = Color.White;
myLabel4.BackColor = Color.White;
myLabel7.BackColor = Color.White;
myLabel9.BackColor = Color.White;
}
}
Thanks in advance
This looks like datetime format issue. Your GridView converts datetime into string in one way and you're trying to convert it back to datetime using different format. Instead of Convert.ToDateTime try using DateTime.ParseExact(String, String, IFormatProvider):
CultureInfo provider = CultureInfo.InvariantCulture;
string format = "dd/MMM/yyyy h:mm tt zzz";
DateTime result = DateTime.ParseExact(dateString, format, provider);
Use format that applies to your case.
Are the textboxes both in the first column of GridView1? For the code:
var myLabel2 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label2");
var myLabel4 = (TextBox)GridView1.Rows[p].Cells[0].FindControl("Label4");
It means the names of your textboxes are "Label2" and "Label4", and they are both in the first column as you use Cells[0] to fetch them. Your have to make sure of that.
You can add break point to the above code, and debug it. You can see if myLabel2 and myLabel4 have any value.
DateTime date = DateTime.ParseExact(myLabel2.Text, "dd/MM/yyyy", null);
I have a date stamp (020920111422) and I want to split it to
day = 02,
month = 09,
year = 2011,
hour = 14,
and minute = 22
Is there a "split string at position" method in C#?
You want:
string x = s.Substring(0, i), y = s.Substring(i);
(or maybe i-1/i+1 depending on your exact requirements).
However, you could also use DateTime.ParseExact to load it into a DateTime by telling it the explicit format:
var when = DateTime.ParseExact("020920111422", "ddMMyyyyHHmm",
CultureInfo.InvariantCulture);
you can do this via SubString - for example:
string myDay = mydatestamp.SubString (0,2);
OR create a DateTime:
DateTime myDateTime = DateTime.ParseExact ( mydatestamp, "ddMMyyyyHHmm" , CultureInfo.InvariantCulture );
Answering on question considering "split string at position" - you can leverage String.Substring(Int32, Int32) method by calling multiple times with different offsets.
Also take a look at LINQ Take() and Skip() methods which allows provide count of elements to return as well.
Otherwise see examples which other guys are provided using DateTime.ParseExact(), I believe this is most correct way to convert string you've provided to DateTime value.
You could also use
var d = DateTime.Parse(s, "ddMMyyyyHHmm");
if the end-goal is a DateTime.
Instead you can convert the date stamp by using Datatime.ParseExact and can extract the day, month, year, hour and minute you want from that date stamp. Refer the following code part for Datetime.ParseExact converting.
DateTime.ParseExact(YourDate, "ddMMyyyyHHmm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None)
For more usecase, maybe this can help
string rawData = "LOAD:DETAIL 11.00.0023.02.201614:52:00NGD ...";
var idx = 0;
Func<int, string> read = count =>
{
var result = rawData.Substring(idx, count);//.Trim();
idx += count;
return result;
};
var type = read(16);
var version = read(8);
var date = read(18);
var site = read(8);
//...
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
txtDatumDokum.Text is like "09.09.2011".
but i get FormatException error. Must i parse date?
Try DateTime.ParseExact with the dd.MM.yyyy format string
DateTime.ParseExact(txtDatumDokum.Text, "yyyyMMdd", CultureInfo.InvariantCulture, DateTimeStyles.None);
It's not good to see, anyway try this:
string s = "09.09.2011";
DateTime dt = Convert.ToDateTime(
s.Replace(".",
new System.Globalization.DateTimeFormatInfo().DateSeparator));
You need to tell us why the text input is using this format. If it is because the user enters it this way, then you need to make sure that the format matches that given by Thread.CurrentCulture.DateTimeFormat.ShortDatePattern. Changing the culture (by setting
Thread.CurrentCulture) to an appropriate value will then solve your problem.
If you are supposed to parse the input no matter what format it is in, then you will need to do some manual processing first (perhaps remove spaces and other delimiter characters from the input with string.Replace) and then try to parse the date using DateTime.ParseExact and a known format string.
But it all depends on why the input has that format, and why your application's current culture does not match it.
You could try this, TryParse avoids parsing exceptions.. Then you just need check result to be sure that it parsed.
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, out datuMDokumenta);
You will have to determine if this is a good solution for your application.
See this example:
http://msdn.microsoft.com/en-us/library/ch92fbc1.aspx
Judging by the date you gave you need to include a culture, de-DE accepts 01.01.11 type of dates but I'm not sure which one you actually want to use, you'll need to decide that.. the Code would look like this:
using System.Globalization;
DateTime datuMDokumenta;
bool result = DateTime.TryParse(txtDatumDokum.Text, CultureInfo.CreateSpecificCulture("de-DE"), DateTimeStyles.None, out datuMDokumenta);
A list of cultures can be found here, select the appropriate one for you:
http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.71%29.aspx
The plus here is that this code is a bit more work but it is very difficult to break. Assuming you are using a free text entry on a TextBox you don't want to be throwing exceptions.
Yes you have to parse input date in current culture.
string[] format = new string[] { "dd.MM.yyyy" };
string value = "09.09.2011";
DateTime datetime;
if (DateTime.TryParseExact(value, format, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.NoCurrentDateDefault, out datetime))
//Valid
else
//Invalid
DateTime dt = Convert.ToDateTime(txtDatumDokum.Text)
It is right...there is no isssue
During a Deserialization call under compact framework 3.5 i've had some unexpected behaviour before.
I've converted from using the OpenNETCF serialization classes to the framework XML serialization class. In doing so, the default time format has changed and the order of property/public members. So long story short, i've exposed a text property which converts my date-times back to the format my VB6 application is expecting.
Dim dumbDate As New Date
Dim formats() As String = {"yyyy-MM-ddTHH:mm:ss.fffzzz", _
"yyyy-MM-dd HH:mm:ss:fffffffzzz"}
_datetimeTaken = dumbDate.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
' There is something wrong with compact framework during the Serialization calls.
' calling the shared method Date.Parse or Date.ParseExact does not produce the same
' result as calling a share method on an instance of Date. WTF?!?!?!
' The below will cause a "Format" exception.
'_datetimeTaken = Date.ParseExact(value, formats, CultureInfo.InvariantCulture, DateTimeStyles.None)
Date.blah doesn't work. dumbDate.blah works. strange.
public static void Main(string[] args)
{
var dt = new DateTime(2018, 04, 1);
Console.WriteLine(dt);
string month = dt.ToString("MMMM");
Console.WriteLine(month); //April
month = dt.ToString("MMM");
Console.WriteLine(month); //Apr
month = dt.ToString("MM");
Console.WriteLine(month); //04
Console.ReadKey();
}
your code:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum.Text);
try changing this to:
DateTime datuMDokumenta = Convert.ToDateTime(txtDatumDokum);
and when u print the date/time
print datuMDokumenta.Text
Any ideas?
I can't come up with any.
I have a list of dates I'm loading in from a csv file and they are saved as all integers, or rather a string of integers (i.e. Jan 1, 2009 = 1012009)
Any ideas on how to turn 1012009 into 1/01/2009?
Thanks!
Since the date is stored as a string, you may want to use ParseExact:
DateTime date = DateTime.ParseExact("28012009", "dMMyyyy", null);
ParseExact will throw an exception if the format doesn't match. It has other overloads, where you can specify more than a single possible format, if that is required. Note that here provider is null, which uses the current culture.
Depending on style you may wish to use TryParseExact.
int date = 1012009;
var month = date / 1000000;
var day = (date / 10000) % 100;
var year = date % 10000;
var formatted = new DateTime(year, month, day).ToString();
This assumes month-day-year; if the numbers are day-month-year, I’m sure you’ll be able to swap the month and day variables to accommodate that.
If you want to customise the date format, you can do so as described in:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
Let 10102009 be dateInt.
string dateString = dateInt.ToString();
int l = dateString.Length;
dateString = dateString.Insert(l-3,"/");
dateString = dateString.Insert(l-6,"/");
You should now have 1/01/2009 in dateString.. You can also try the ParseExact function..