How to retrieve formatted version of date from date picker backend - c#

I have a date picker and time picker I am using in my iOS application (using xamarin) and I am trying to retrieve the date and time selected by the user to use elsewhere in the code. My problem is that I am not sure how to retrieve just the date or just the time. For example I have this following code to retrieve the date:
// not getting proper date format!
var selectedDate = ContactDatePicker.Date.ToString ();
var selectedTime= ContactTimePicker.Date.ToString ();
Console.WriteLine ("Here: {0}, {1}", selectedDate, selectedTime);
But it outputs the entirety of the of the date and time for each variable like so:
Here: 2016-05-24 15:18:50 +0000, 2016-05-24 15:18:50 +0000
I would like to get something like 2016-05-24 for date or something like 15:18:50 for time. I realize I can use regex for this but I was wondering if there is a simple way to format dates.

Since UIDatePicker.Date returns nsdate you could convert it to DateTime first and supply required format to ToString method.
var dateTime = DateTime.SpecifyKind(ContactTimePicker.Date, DateTimeKind.Unspecified);
var selectedDate = dateTime.ToString("yyyy-MM-dd");
var selectedTime= dateTime.ToString("HH:mm:ss");

If ContactDatePicker.Date type is DateTime you can use ToShortDateString() and ToShortTimeString() or ToLongTimeString:
var selectedDate = ContactDatePicker.Date.ToShortDateString();
var selectedTime = ContactTimePicker.Date.ToLongTimeString();
//Output:
2016-05-24
15:18:50
According to documentation of UIDatePicker, Date property returns a NSDate, but there are an implicit conversion to DateTime, so you can do something like this:
DateTime date = ContactDatePicker.Date //Implicit conversion
var selectedDate = date.ToShortDateString();
var selectedTime = date.ToLongTimeString();

Thanks for the info guys I ended up using:
// explicitly convert NSDate to DateTime to change format
DateTime date = (DateTime)ContactDatePicker.Date;
DateTime time = (DateTime)ContactTimePicker.Date;
// able to overload ToString() method with argument to change format
var selectedDate = date.ToString ("d");
var selectedTime = time.ToString ("HH:mm:ss");

Related

I need only date value part and time value part using ASP.NET C#

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

Get only the date from a datetime in c#

I'm trying to pass a date in a viewbag like this
DateTime? DueDate = this.dbContext.OBProcessMonitors.Where(o => o.EmployeeID
== GlobalVariables.EmployeeID).First().DueDate;
ViewBag.DueDate = DueDate;
WHen i call the viewbag in razor #viewbag.duedate i get the date and time. How can I get just the date out of it?
Use 'DueDate.Value.Date' to get just the date of a datetime.
I assume that you need a date string, not a date object. So do following
To get short date string: like "6/15/2009" in en-US
Value.ToShortDateString()
Or to get long date string: like "Monday, June 15, 2009"
Value.ToLongDateString()
Or using custom format
Value.ToString("d")
Check other formats here: https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx
You can convert DateTime to string and format it however you want to:
ViewBag.TheDate = yourobject.DueDate.ToString("dd/MM/yyyy") //or,
ViewBag.TheDate = yourobject.DueDate.ToString("MM/dd/yyyy") //or,
ViewBag.TheDate = yourobject.DueDate.ToString("yyyy/MM/dd") //etc...

datetime conversion issue when i specify format

My code throws an error:
When converting string to datetime, parse the string to take the date before putting each variable into datetime object.
CODE:
I need to display default value in text box i.e. current date.
txtIssuingDate.Text = DateTime.Now.ToString("dd/MM/yyyy");
Then i need to save that in DB too without in specified format
ComposedLetterBizz CompLetterBizz = new ComposedLetterBizz(Convert.ToInt32(txtName.Text),
Convert.ToInt32(HiddenFieldComplaintID.Value),
txtLetterNo.Text,
txtDispatchNo.Text,
txtSubject.Text,
Convert.ToInt16(ddlDepartments.SelectedValue),
Convert.ToInt16(ddlDesignations.SelectedValue),
Convert.ToDateTime(txtIssuingDate.Text),
Convert.ToDateTime(txtDeadLine.Text));
Use DateTime.Parse with CultureInfo.InvariantCulture in case that your culture doesn't use / as date-separator:
So instead of
Convert.ToDateTime(txtIssuingDate.Text)
which uses your current-culture's date-separator, this
DateTime.Parse(txtIssuingDate.Text, CultureInfo.InvariantCulture)
But then you should also do it when you assign the date to the TextBox.Text:
txtIssuingDate.Text = DateTime.Now.ToString(CultureInfo.InvariantCulture);
The "/" Custom Format Specifier
try this
DateTime obj = DateTime.Now;
txtIssuingDate.Text = obj.ToString("dd/MM/yyyy");
ComposedLetterBizz CompLetterBizz = new ComposedLetterBizz(Convert.ToInt32(txtName.Text), Convert.ToInt32(HiddenFieldComplaintID.Value), txtLetterNo.Text, txtDispatchNo.Text, txtSubject.Text, Convert.ToInt16(ddlDepartments.SelectedValue), Convert.ToInt16(ddlDesignations.SelectedValue),
obj, Convert.ToDateTime(txtDeadLine.Text));

Converting System Date Format to Date Format Acceptable to DateTime in C#

How can I convert a system date format (like 3/18/2014) to the format readable in DateTime?
I wanted to get the total days from two dates, which will come from two TextBoxes.
I have tried this syntax:
DateTime tempDateBorrowed = DateTime.Parse(txtDateBorrowed.Text);
DateTime tempReturnDate = DateTime.Parse(txtReturnDate.Text);
TimeSpan span = DateTime.Today - tempDateBorrowed;
rf.txtDaysBorrowed.Text = span.ToString();
But tempDateBorrowed always returns the minimum date for a DateTime varibale. I think this is because DateTime does not properly parse my system date format. As a consequence, it incorrectly displays the number of days. For example, if I try to enter 3/17/2014 and 3/18/2014 respectively, I always get -365241 days instead of 1.
Edit: I wanted my locale to be non-specific so I did not set a specific locale for my date format. (My system format by the way is en-US)
Try DateTime.ParseExact method instead.
See following sample code (I've used strings instead of TextBoxes since I used a Console app to write this code). Hope this helps.
class Program
{
static void Main(string[] args)
{
string txtDateBorrowed = "3/17/2014";
string txtReturnDate = "3/18/2014";
string txtDaysBorrowed = string.Empty;
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed, "M/d/yyyy", null);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate, "M/d/yyyy", null);
TimeSpan span = DateTime.Today - tempDateBorrowed;
txtDaysBorrowed = span.ToString();
}
}
ToString is not Days
TimeSpan.TotalDays Property
You can try specifying the format of the datetime in the textboxes like this
DateTime tempDateBorrowed = DateTime.ParseExact(txtDateBorrowed.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
DateTime tempReturnDate = DateTime.ParseExact(txtReturnDate.Text.Trim(), "M/d/yyyy", CultureInfo.InvariantCulture);
Also you may have to check if the values from the textboxes are valid.
My first thought is to just replace the TextBox controls with a DateTimePicker or equivalent, depending on what platform you're developing on. Converting strings to dates or vice-versa is more of a pain than it seems at first.
Or you could try using DateTime.ParseExact instead, to specify the exact expected format:
DateTime tempDateBorrowed =
DateTime.ParseExact("3/17/2014", "M/dd/yyyy", CultureInfo.InvariantCulture);
Or you could specify a specific culture in the call to DateTime.Parse:
var tempDateBorrowed = DateTime.Parse("17/3/2014", new CultureInfo("en-gb"));
var tempDateBorrowed = DateTime.Parse("3/17/2014", new CultureInfo("en-us"));
try formatting your date to iso 8601 or something like that before parsing it with DateTime.Parse.
2014-03-17T00:00:00 should work with DateTime.Parse. ("yyyy-MM-ddTHH:mm:ssZ")
Try this:
if(DateTime.TryParseExact(txtDateBorrowed.Text, "M/d/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None, out tempDateBorrowed))
{
TimeSpan span = DateTime.Today - tempDateBorrowed;
}

How to get today's date in mm/dd/yyyy format into a datetime variable in c#

I want today's date in mm/dd/yyyy format from a DateTime variable. How to get it?
I need to check this with some date variable so it must be also in date variable format?plz help
Ex: i need to get today date in mm/dd/yyyy format and i already date which is datetime datatype in mm/dd/yyyy format and i have to compare them
You should use DateTime.Today:
DateTime today = DateTime.Today; // As DateTime
string s_today = today.ToString("MM/dd/yyyy"); // As String
Edit: You edited your post to add another question, so here comes my edit to supply at least some sort of answer.
Update While you can use DateTime.Compare() you should use plain comparisson:
if(today < otherdate)
{
// Do something.
}
Alternatively, you can use DateTime-variables to check against other DateTime-variables using the DateTime.Compare() method. Both otpions will work and it comes down to preference and what you want to do with the result.
int result = DateTime.Compare(today, otherdate);
if(result < 0)
MessageBox.Show("Today is earlier than the 'otherdate'");
elseif(result > 0)
MessageBox.Show("Today is later than the 'other date'");
else
MessageBox.Show("Dates are equal...");
string datestring = DateTime.Now.ToString("MM/dd/yyyy");
MSDN say: Custom Date and Time Format Strings
To convert DateTime variable to string in the specified format:
DateTime d = ...;
string s = d.ToString("MM/dd/yyyy");
If you want to compare only date part of DateTime, not time part:
DateTime d1 = DateTime.Parse("10/10/2011");
DateTime d2 = DateTime.Parse("01/01/2011");
if (d1.Date > d2.Date)
{
// do the stuff
}
DateTime.Now.ToString("MM/dd/yyyy");
DateTime.Today.ToString("MM/dd/yyyy");
DateTime.Parse is what you are looking for...

Categories