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
}
Related
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"));
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.
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 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);
I am using the Vimeo API and I want to convert the string <upload_date> to a short date format, {0:d} or {0:dd/mm/yyyy}.
This is my code but it doesn't seem to be working for me.
select new VimeoVideo
{
Date = String.Format("{0:d}",(item.Element("upload_date").Value)),
};
return Vids.ToList();
}
public class VimeoVideo
{
public string Date { get; set; }
}
As Oleg suggested you can try to parse your value to DateTime and then format it (use try catch if needed). That should work (not 100% sure since I don't know what item's type is).
var myDate = DateTime.Parse(item.Element("upload_date").Value);
Date = String.Format("{0:d}", myDate);
http://msdn.microsoft.com/it-it/library/1k1skd40(v=VS.80).aspx
Just verify the type of the Value property.. The above string formatter works for System.DateTime structure.. I assume in your case its string type object. According to the given sample date time string i have written this code.. Try out this.
CultureInfo provider = CultureInfo.InvariantCulture;
var format = "yyyy-MM-dd HH:mm:ss";
var dt = DateTime.ParseExact(item.Element("upload_date").Value, format, provider);
Date = string.Format("{0:d}", dt);
Hope it works..