how can i get the date in this format "30-jun-2013"
at runtime if user type in the above format in the textbox ..it will fetch the matching rows of data for the specified date and filter that and show in datagridview
so for that i want to compare the date format with the text typed in textbox
string todaydate = Convert.ToString(DateTime.Today);
DateTime DTM = Convert.ToDateTime(todaydate);
string datetoday = DTM.ToString("dd-MMM-yyyy");
if (TypeHereTextBox.Text == datetoday)
{
OLCMND2 = new OracleCommand("Select * from TABLENAME where DATE = '" + typeHereTextBox.Text + "'", CON);
OADAP1 = new OracleDataAdapter(OLCMND2);
OADAP1.Fill(DTBLE2);
DatagridView.DataSource = DTBLE2;
}
how can it be solved
hi i got the solution guys
string[] arrayData = TextBox.Text.Split('-');
if (arrayData.Length == 3)
OLCMND2 = new OracleCommand("Select VISITORCOUNT,REMARKS,to_date(to_char(TODAYDATE, 'DD-MON-YYYY'),'DD-MON-YYYY') AS TODAYDATE,CARDNUMBER,PHOTO from VMS_VISITOR where TODAYDATE = TO_DATE('" + TypeHereTextBox.Text + "','dd-MON-yyyy')", CON);
OADAP1 = new OracleDataAdapter(OLCMND2);
OADAP1.Fill(DTBLE2);
DatagridView.DataSource = DTBLE2;
Thanks for all your responses guys
This will parse from that format:
var dateToParse = "30-Jun-2013"; //TypeHereTextBox.Text
var parsedDate = DateTime.ParseExact(dateToParse, "dd-MMM-yyyy", CultureInfo.InvariantCulture);
if (parsedDate.Date == datetoday.Date)
{
// Do stuff
note - June only has 30 days ;)
The best approach would be check for date month and year separately with the today's date. if it matches , then concatenate the date month and year in the format you want and pass to the query.
I would not compare date as strings, fist convert string to DateTime using DateTime.ParseExact by giving datetime format string. then compare two datetime objects instead of string comparison.
And also I would use parameters to set the Date column value as below
OLCMND2 = new OracleCommand("Select * from TABLENAME where DATE = :dateVal", CON);
OLCMND2.Parameters.Add("dateVal", OracleDbType.Date
, myDatetime, System.Data.ParameterDirection.Input);
first of all you are doing string compare, which means you compare the references. please use
if (TypeHereTextBox.Text.Equals(datetoday))
instead.
second, why not comparing dateTime and not strings?
because your data isn't a valid date anyway then you can't use ParseExact or TryParseExact but woth any valid date you can do:
DateTime d;
DateTime.TryParseExact(date, "dd-MMM-yyyy", System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.NoCurrentDateDefault, out d);
if (d== DTM)
Related
I have a string ("CompletionDate") which contains the value "2/28/2017 5:24:00 PM"
Now I have 2 variables (EDate and ETime). I want to assign the Date to EDate (i.e 2/28/2017) and Time to ETime (i.e. 5:24:00 PM).
How can I split the Date and Time from a single string.
Kindly Help.
My approach right now is like :
string CompletionDate = string.Empty;
string ProjectEDate = string.Empty;
string ProjectETime = string.Empty;
CompletionDate = "2017-03-29 12:58:00";
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd", CultureInfo.CreateSpecificCulture("en-us"));
DateTime dt1 = DateTime.ParseExact(CompletionDate, "HH:mm:ss", CultureInfo.CreateSpecificCulture("en-us"));
var ProjectEDate = dt.ToString();
var ProjectETime = dt1.ToString();
But its throwing exception that string is not in correct format. Kindly help
#Chris pointed one of your problems, but you have one more. You are passing full date time string and trying to treat it as date or time only, which is not true. Instead I suggest you to parse DateTime object with both date and time, and then take whatever you need from parsed object:
CultureInfo enUS = CultureInfo.CreateSpecificCulture("en-us");
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", enUS);
var ProjectEDate = dt.Date.ToString();
var ProjectETime = dt.TimeOfDay.ToString();
You need to specify the full format as same as the input string to parse method.
DateTime dt = DateTime.ParseExact(CompletionDate, "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CreateSpecificCulture("en-us"));
To get results you can use below methods available by default in DateTime.
dt.ToShortTimeString()
"12:58 PM"
dt.ToLongTimeString()
"12:58:00 PM"
dt.ToLongDateString()
"Wednesday, March 29, 2017"
dt.ToShortDateString()
"3/29/2017"
Or you can specify the format to ToString method.
dt.ToString("yyyy-MM-dd")
"2017-03-29"
dt.ToString("HH:mm:ss")
"12:58:00"
DateTime.ParseExact(CompletionDate, "yyy-MM-dd", ...
You are missing 4th 'y' in date format string:
"yyyy-MM-dd"
^
here
and:
String was not recognized as a valid DateTime " format dd/MM/yyyy"
Why do you parse into DateTime and then convert to a string using ToString again? CouldnĀ“t you just simply use String.Split when all you want is to split the time from the day and you know the exact format?
var CompletionDate = "2017-03-29 12:58:00";
var tmp = CompletionDate.Split(' ');
var ProjectEDate = tmp[0];
var ProjectETime = tmp[1];
I have a string that represents a time formatted as "HH:mm", say for example "8:15" (assuming the time is in 24 hour format). In C#, How can I convert that into a DateTime instance where the date is today's date and the time is 8:15 AM?
string ds = "8:15";
string[] parts = ds.Split(new[] { ':' });
DateTime dt = new DateTime(
DateTime.Now.Year,
DateTime.Now.Month,
DateTime.Now.Day,
Convert.ToInt32(parts[0]),
Convert.ToInt32(parts[1]));
DateTime.Parse(DateTime.Now.Date.ToString() + " " + yourString);
string time ="8:15";
DateTime date = DateTime.Parse(DateTime.Now.ToString("M/d/yyyy ") + time);
Assuming situation for current date:
string time ="8:15";
var dt = Convert.ToDateTime(String.Format("{0} {1}",
DateTime.Now.ToShortDateString(),time));
If you have a valid date in string then, you can use. Also you can use DateTime.TryParse() to check for a valid date.
var date ="01/01/2014";
var dt = Convert.ToDateTime(String.Format("{0} {1}",
date,time));
You will get output
01/06/2014 08:15:00
You can probably parse the time using TimeSpan.ParseExact and then add it to today's date by
using DateTime.Add.
Given that your time is in a variable like this:
var timeText = "8:15";
Parse the time like this:
var time = TimeSpan.ParseExact(timeText, "h:mm", /*todo*/);
Fill the last argument depending on your requirements.
Then add it to today's date:
DateTime.Today.Add(time);
Is there any way I don't have to specify the number of digits in day/month/year?
For e.g 1/2/1991
I want a method which satisfies both 1/2/1991,11/3/1990,12/12/1991
I don't know how many digits will be there in either month, year, or days.
My code is
string copy = splittedData[0] + splittedData[1] + splittedData[2];//date+month+year
DateTime datetime = DateTime.ParseExact(copy, "ddMMyyyy", CultureInfo.InvariantCulture);
DateTime dateAndTime = datetime;
The problem is the number of digits in splitted data array are not known to me and thus the above format "ddMMyyyy" give me exception on some cases.
Since you already have the day month and year then just create a date with the three of them like so;
DateTime date = new DateTime(year, month, day);
No parsing is necessary. You already have all the fields you want to create the date, and you dont need to put it into a special format to create a date.
If you are not sure the if the input is valid, then wrap the creation in a try/catch block to catch an ArgumentOutOfRangeException should it should occur.
Since you updated your question with the code you have, you can concatenate date components with a separator like:
string copy = splittedData[0] + "/" + splittedData[1] + "/" + splittedData[2];
Later you can do:
DateTime dt = DateTime.ParseExact(copy, "d/M/yyyy", CultureInfo.InvariantCulture);
I used the format "d/M/yyyy" with single d and M which would account for both single/double digit day/month.
So it will work for dates like:
01/01/2013
1/01/2013
22/09/2013
02/9/2013
DateTime.ParseExact is specifically intended to not allow what you are asking for. DateTime.Parse will allow it, though.
You say you have the 3 parts as separate strings -- if you insert the /'s and parse, it should succeed (InvariantCulture expects the order month-day-year):
string datetimeString = string.Join("/", new[] {month, day, year});
DateTime datetime = DateTime.Parse(datetimeString, CultureInfo.InvariantCulture);
Or you could convert them to integers and construct a DateTime directly:
DateTime datetime = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), Convert.ToInt32(day));
What #n00b said. You've already got the individual components of the date: why are you globbing them back together just so you can call DateTime parsing routines? Just do something like this:
private static DateTime StringToDateTime( string year , string month , string day )
{
int yyyy = int.Parse(year) ;
int mm = int.Parse(month) ;
int dd = int.Parse(day) ;
DateTime dt = new DateTime(yyyy,mm,dd) ;
return dt ;
}
As an added bonus, The above code will probably run faster than DateTime.Parse() or DateTime.ParseExact().
Guys I have a string having a date in the format dd/mm/YYYY.
However I need to use it a datetimepicker control.
I cannot assign the value to the datetimepicker, i tried as
string exp = "SELECT UserPwdExpiry FROM " + MainForm.schema + "Adm.SysUser WHERE USerId ='" + cmbUserID.Text + "'";
cmd = ccs.CreateCommand();
ccs.Open();
cmd.CommandText = exp;
DateTime expiry_ = ((DateTime)cmd.ExecuteScalar());
//string _expiry_= expiry_.ToShortDateString();
ccs.Close();
assigning here
dtpPasswordExpiry.Value = Convert.ToDateTime(_expiry_);
It gives me an error saying, FORMAT SHOW BE BETWEEN MaxDate and MinDate.
Help please.
if DateTime expiry_ = ((DateTime)cmd.ExecuteScalar()); this line running without errors you already have Datetime object. So you can directly set it as
tpPasswordExpiry.Value =expiry_;
But above line will fail if you store datetime as string in database then
string _User_modify= (string)cmd.ExecuteScalar();
DateTime dt;
if(DateTime.TryParseExact(_User_modify,
"dd/MM/YYYY",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt))
{
tpPasswordExpiry.Value =dt;
}
We already have:
DateTime expiry = ((DateTime)cmd.ExecuteScalar());
so: we know the value is a DateTime. The DateTimePicker control's .Value property is a DateTime, so the correct syntax here is:
dtpPasswordExpiry.Value = expiry;
The only thing that leaves, based on the error message, is the MinDate and MaxDate. I suspect you need to change the values of those two properties such that your expiry is a legal value not outside the range MinDate - MaxDate. If unsure, simply print out the values of expiry, dtpPasswordExpiry.MinDate and dtpPasswordExpiry.MaxDate.
How can I remove time from datetime and store the output in datetime format? I do not want to show the time.
Say I have
string d = "2/27/2013 4:18:53 PM"
How can I store the output in a DateTime variable with only the date and not time.
I can use ToShortDateString() but then it return a string and not datetime.
My ultimate goal is to sort the date column chronologically which can only be done if all the entries are in datetime format and not string.
The Date property of the DateTime struct will give you a date but it will always have a time component that represents midnight ("00:00:00"). If you're starting with a string, you might be able to work with something like this:
DateTime d = DateTime.Parse("2/27/2013 4:18:53 PM").Date; // 2/27/2013 12:00:00 AM
Just make sure you perform your comparison on DateTime objects (i.e. omit all usages of ToString()).
Alternatively, you can format your date in the "sortable" time format:
string d = DateTime.Parse("2/27/2013 4:18:53 PM").ToString("s");
or
string d = yourDateTime.ToString("s");
For the above case d would be 2013-02-27T16:18:53. When sorted alphabetically, the strings will be in chronological order.
DateTime dt = DateTime.now(); (To get Any Date)
string datewithMonth= dt.ToString("MMMM dd, yyyy");
string onlyDate = DateTime.Parse(datewithMonth).ToShortDateString();
Here we get result as 1/1/2014. So that we can perform select operation on sql like this:
searchQuery = "select * from YourTableName where ColumnName = ' " + onlyDate + " ' ";
What about removing the time in culture:-
var submissionDateData = DateTime.Now.ToShortDateString();
var submissionDate = DateTime.Parse(submissionDateData, CultureInfo.CreateSpecificCulture("en-GB"));
First line gives 02/11/2015
Second line gives 11/02/2015 12:00:00 AM
Do you have to do a string split on this or is there a way to get rid of the time?
As easy as this:
d.ToString("mm/dd/yyyy");
DateTime date = DateTime.Parse(d);