Converting an inputted string into a date - c#

I have been trying to get a date conversion to wrok to convert from a string to a date I have looked at msdn and some other stack o questions but multiple ways have not worked. I am making a console app and it needs a valid date to check other dates. below is my current attempt.
string StartDate, EndDate;
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
StartDate = DateTime.Parse(StartDate);
I currently set the variable StartDate and then set it a value depending on what the user enters and then it should change this to a date using the Parse

you are trying to assign the DateTime value to string StartDate, which is wrong. So change it like below:
string StartDate, EndDate;
DateTime date;
Console.WriteLine("Input Start date");
StartDate = Console.ReadLine();
date = DateTime.Parse(StartDate);

A string is not a DateTime and a DateTime not a String. So you might be able to parse a string to a date but you cannot use the string variable for the DateTime and vice-versa. You need two variables:
string startDateInput = Console.ReadLine();
DateTime startDate = DateTime.Parse( startDateInput );
Since this could fail if the input string is not a valid date you should use TryParse:
DateTime startDate;
bool validDate = DateTime.TryParse(startDateInput, out startDate);
if(validDate)
Console.Write("Valid date: " + startDate.ToLongDateString());

Try using Convert.ToDateTime();
Example:
string date = "01/08/2008";
DateTime dt = Convert.ToDateTime(date);

Use DateTime.TryParse()
Converts the specified string representation of a date and time to its
DateTime equivalent and returns a value that indicates whether the
conversion succeeded.
DateTime date;
if (!DateTime.TryParse("DateString", out date))
{
MessageBox.Show("Invalid string!");
}

You need to specify the Date Format.
Try This: Example format MM-dd-yyyy
Console.WriteLine("Input Start date Format -> MM-dd-yyyy");
string StartDate = Console.ReadLine();
DateTime YourDate = DateTime.ParseExact(StartDate,"MM-dd-yyyy",
System.Globalization.CultureInfo.InvariantCulture);

Related

Convert date and time into Correct format to compare to current date

I have a date in this format "2017-03-29" and time like "09:30", How do I conver toDatetime.
Following is how I have
string date = "2017-03-29";
string time = "09:30"
I need to convert this to DateTime in c#.
I also need to compare this converted DateTime with current dateTime, I will be using this in comparison in Linq
Use DateTime.ParseExact. Also your problem statement and code shown have nothing to do with Linq. The code below assumes the hours are in 24 hour format, adjust accordingly if that is not the case and provide an am/pm flag.
string date = "2017-03-29";
string time = "09:30";
var dateTime = DateTime.ParseExact(date+time, "yyyy-MM-ddHH:mm", null);
I would say the same as #Sam, but I don't have enough reputation to comment.
string date = "2017-03-29";
string time = "09:30";
string dateTimeString = string.Format("{0} {1}", date, time);
DateTime dateTime = DateTime.ParseExact(dateTimeString, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture);
Note that the Kind of the resulting DateTime is DateTimeKind.Unspecified. Convert it as necessary.
Using the variables provided:
string dateTime = date + " " + time;
DateTime d = Convert.ToDateTime(dateTime);

Convert Java Date to DateTime not work in Xamarin

I have the Date and Time like this 2016/11/28 and time 07:30 PM. And combine this string and make like below
string mydate = extras.GetString("Apodate") + " " + extras.GetString("Apostarttime");
so mydate string contain 2016/11/28 07:30PM.
No I want to convert this string to below format
"yyyy-MM-dd'T'HH:mm:ss'Z'"
So I try this way:
SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm a");
try
{
Java.Util.Date startdate = dateFormat.Parse(mydate);
Java.Util.Date enddate = dateFormat.Parse(mydate1);
SimpleDateFormat rformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
DateTime dt1 = DateTime.ParseExact(rformat.Format(startdate).ToString(), "yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
model.StartTime = dt1;
}
catch (ParseException e)
{
e.PrintStackTrace();
}
But my model.StartTime contain 12/11/0195 7:30:00 PM. But I want
2016/11/28 7:30:00 PM. as a DateTime.
First the thing you should consider to do is
1. Convert String(type) To DateTime(type)
- Search how parseExact do first, I think "yyyy-MM-dd'T'HH:mm:ss'Z'" is not the correct datetime format
2. When you got Datetime(type) you can display to any string format you want
- Search how to convert type DateTime to string
Link
https://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp#=
How do I get the AM/PM value from a DateTime?
TLDR;
SimpleDateFormat rformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss ");//Format text as what ParseExact method can do
DateTime dt1 = DateTime.ParseExact(rformat.Format(startdate).ToString(), "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);//plz become Datetime!!! And don't give me a runtime error here
model.StartTime = dt1;
And when you want to display model.StartTime
string Datetxt = model.StartTime.ToString("yyyy/MM/dd'T'HH:mm tt'Z'", CultureInfo.InstalledUICulture) //now become a beautiful string with unwanted chars 'T' and 'Z'

How to convert informal string value to Date time in c#

All of my friend.
I want to convert informal string to dateTime in c#. Here my string value is "01042016".How can convert? can i need another step to change DateTime.
This is my code:
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate = Convert.ToDateTime(splitDate[0].ToString(),"dd/MM/yyyy"));
As we can see that the input date will be in the format ddMMyyyy so here the best option for converting the input to DateTime object is DateTime.TryParseExact the code for this will be :
string FinancialYear = "01042016-31032017";
string[] splitDate = FinancialYear.Split('-');
DateTime startDate ;
if(DateTime.TryParseExact(splitDate[0],"ddMMyyyy",CultureInfo.InvariantCulture,DateTimeStyles.None,out startDate))
{
// Proceed with the startDate it will have the required date
}
else
// Show failure message
This will create an Enumerable where index 0 is the first date and index 1 is the second date.
string FinancialYear = "01042016-31032017";
var dateRange = FinancialYear.Split('-')
.Select(d => DateTime.ParseExact(d, "ddMMyyyy", CultureInfo.InvariantCulture);
If you are not sure of the format your best bet is using DateTime.Parse() or DateTime.TryParse()
You are not 100% guaranteed that the date will be parsed correctly, especially in cases where the day and month numbers could be in the wrong order.
It is best to specify a required date format if you can so you can be sure the date was parsed correctly.
if you string is in static format, you can convert it by reconvert it to valid string format first such as
string validstring = splitDate[0].ToString().Substring(4,4)+"-"+splitDate[0].ToString().Substring(2,2) +"-"+ splitDate[0].ToString().Substring(0,2);
DateTime startDate = Convert.ToDateTime(validstring,"dd/MM/yyyy"));

Getting date in correct formatted for with proper timezone, among list of strings in an a array

I have a set of array.
//this is not hard corded, some times array will have multiple no.of strings in date format.
["vishnu","2016-08-31T18:30:00.000Z","1992","banglore"]
I have an array of strings, among these strings there is one string which is in date format.
I need to do a foreach and need to check which string is in the date format.
If we got the date string "2016-08-30T18:30:00.000Z" I need to convert it to basic date format but in correct timezone, here the date is 2016-08-31 but what I need as out put is
["vishnu","31/8/2016","1992","banglore"]
not
//check the difference in date!
["vishnu","30/8/2016","1992","banglore"]
the aim is from the array, if string is in date string format, convert it.
public static void Main(string[] args)
{
string inputString = "2016-08-31T18:30:00.000Z";
DateTime enteredDate = DateTime.Parse(inputString);
Console.WriteLine(enteredDate);
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime dtx = enteredDate.ToLocalTime();
String.Format("{0:d/MM/yyyy}", dDate);
Console.WriteLine(dtx);
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
// DateTime dt = convertedDate.ToLocalTime();
}
If you need to correct the DateTime for the time zone, you can use TimezoneInfo.ConvertTime():
string inputString = "2016-08-31T18:30:00.000Z";
DateTime dDate;
if (DateTime.TryParse(inputString, out dDate))
{
DateTime correctedDateTime = TimeZoneInfo.ConvertTime(dDate, TimeZoneInfo.Local);
// write this here back into the array using your format
Console.WriteLine(correctedDateTime.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture));
}
else
{
Console.WriteLine("Invalid"); // <-- Control flow goes here
}
For further reference check out this post. This answer is inspired by it to use TimeZoneInfo.
DateTime dDate;
do this operation iside foreach
if (DateTime.TryParse(answerString, out dDate))
{
DateTime enteredDate = DateTime.Parse(answerString);
var Date = enteredDate.ToString("dd/MM/yyyy");
answerString = Date;
Console.WriteLine(answerString);
}
else{
//operation
}
thanks to mong zhu
Try using DateTimeOffset rather than DateTime as it is built to handle time zones.
Here's the code:
string inputString = "2016-08-31T18:30:00.000Z";
DateTimeOffset enteredDate = DateTimeOffset.Parse(inputString);
Console.WriteLine(enteredDate);
DateTimeOffset dtx = enteredDate.ToLocalTime();
Console.WriteLine(dtx);
This produces the following for me in GMT+09:30:
2016/08/31 18:30:00 +00:00
2016/09/01 04:00:00 +09:30
To get it in Indian time try this:
DateTimeOffset dtx = enteredDate.ToOffset(TimeSpan.FromHours(5.5));
Console.WriteLine(dtx);
I get 2016/09/01 00:00:00 +05:30 now.

Add the current time to a DateTime?

I have a string which represents a date, its given back from a DropDownList. The string is "27.08.2010" for example. Now I want to add the current time to this and parse it to Datetime ... so in the end it should be a DateTime like 27.08.2010 15:12:45 for example.
How could I do this? Right now, I am putting together a string using DateTime.Now.Hour etc. and make a DateTime out of it, but that seems to be the wrong way.
Thanks :)
string s = "27.08.2010";
DateTime dt = DateTime.ParseExact(s, "dd.MM.yyyy", CultureInfo.InvariantCulture);
DateTime result = dt.Add(DateTime.Now.TimeOfDay);
You can parse the string into a DateTime instance then just add DateTime.Now.TimeOfDay to that DateTime instance.
DateTime date = DateTime.ParseExact("27.08.2010", "dd.MM.yyyy", System.Globalization.CultureInfo.InvariantCulture);
TimeSpan time = DateTime.Now.TimeOfDay;
DateTime datetime = date + time;

Categories

Resources