How to convert date string to specific date format? - asp.net

I get date string value(3/13/2013 12:00:00AM) from database and i need to convert like this format (yyyy-mm-dd). Please help me solve this.
string targetdate = "3/13/2013 12:00:00AM";(getting date value from DB)
DateTime lastdate = DateTime.ParseExact(targetdate, "yyyy-mm-dd",
System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
And I tried
Iformatprovider = null.
but i getting same error "String was not recognized as a valid DateTime"

I think the problem is with the date time
"3/13/2013 12:00:00AM"
It should not be 12:00:00AM.
It should be 12:00:00PM.
Example
string targetdate = "3/13/2013 11:59:59AM";
DateTime lastdate = DateTime.ParseExact(targetdate,
"M/d/yyyy HH:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture);
lastdate=lastdate.AddSeconds(1);
You will get
3/13/2013 12:00:00 AM
I would suggest you to cast it in the database end.
If you are using sql server then
Example
The following script uses the CONVERT() function to display different formats. We will use the GETDATE() function to get the current date/time:
CONVERT(VARCHAR(19),GETDATE())
CONVERT(VARCHAR(10),GETDATE(),10)
CONVERT(VARCHAR(10),GETDATE(),110)
CONVERT(VARCHAR(11),GETDATE(),6)
CONVERT(VARCHAR(11),GETDATE(),106)
CONVERT(VARCHAR(24),GETDATE(),113)
The result would look something like this:
Nov 04 2011 11:45 PM
11-04-11
11-04-2011
04 Nov 11
04 Nov 2011
04 Nov 2011 11:45:34:243

First you need to convert your date string to DateTime type object using the format "M/d/yyyy HH:mm:sstt" later you can get the formatted string using "yyyy-MM-dd". (You used lower case m for month, it should be upper case M for month.
string targetdate = "3/13/2013 12:00:00AM";
DateTime lastdate = DateTime.ParseExact(targetdate,
"M/d/yyyy hh:mm:sstt",
System.Globalization.CultureInfo.InvariantCulture);
string newFormat = lastdate.ToString("yyyy-MM-dd");
newFormat would contain "2013-03-13"

DateTime conversion is really easy in .Net if you know which datetime format you have and in which format you convert that.
Here is example for this.
String origionalDate = "12/20/2013"; // Format : MM/dd/yyyy
string origionalFormat = "MM/dd/yyyy";
string convertInToFormat="dd/MM/yyyy";
String convertedDate;
DateTime objDT;
if (DateTime.TryParseExact(origionalDate, origionalFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out objDT) == true)
{
convertedDate = objDT.ToString(convertInToFormat);
Response.Write("<b>Origional DateTime Format ( " + origionalFormat + " ) : </b>" + origionalDate);
Response.Write("<br/>");
Response.Write("<b>Converted DateTime Format ( " + convertInToFormat + " ) : </b>" + convertedDate);
}
else
{
Response.Write("<b>Not able to parse datetime.</b>");
}
For more details on this visit this link. Click Here...

Related

Parse string to DateTime in Flutter (Dart) [duplicate]

This question already has answers here:
How do I convert a date/time string to a DateTime object in Dart?
(8 answers)
Closed 1 year ago.
I am trying to parse String formatted like "23.1.2020" to DateTime object, but nothing works for me. I tried to use some packages like intl or date_format, but none of these can do the job.
DateTime todayDate = DateTime.parse("12.04.2020");
formatDate(todayDate, [yyyy, '/', mm, '/', dd, ' ', hh, ':', nn, ':', ss, ' ', am])
Do you have any idea, how to parse this?
Ok, I found way how to do that:
import 'package:intl/intl.dart';
DateFormat format = DateFormat("dd.MM.yyyy");
print(format.parse(date));
If you are absolutely sure that your date format will always be "dd.MM.yyyy" you could do this :
DateTime todayDate = DateTime.parse("12.04.2020".split('.').reversed.join());
This trick will format your date to "yyyyMMdd" format, which, according to the docs, is accepted by DateTime.parse().
Try out this package, Jiffy, it also runs on top of Intl, but makes it easier using momentjs syntax. See below
var date = Jiffy("12.04.2020", "dd.MM.yyyy").format("dd, Oct yy"); // 12, Apr 20
You can also do the following default formats
var date = Jiffy("12.04.2020", "dd.MM.yyyy").yMMMMd; // April 12, 2020
Hope this helps
Fuction Convert date to string :
String dateTostring(DateTime datevalue)
{
String _stringdate ="";
_stringdate = datevalue.month.toString()+"."+datevalue.day.toString()+"."+datevalue.year.toString() ;
return _stringdate;
}
Then fuction convert string to date:
DateTime dateStringtodate(String stringdate)
{
DateTime _stringdate;
List<String> validadeSplit = stringdate.split('.');
if(validadeSplit.length > 1)
{
int day = int.parse(validadeSplit[1].toString()));
int month = int.parse(validadeSplit[0].toString());
int year = int.parse(validadeSplit[2].toString());
_stringdate = DateTime.utc(year, day, month);
}
return _stringdate;
}

datetime parsing from excel sheet in asp.net

i want to get a datetime value from excel sheet and take the highest and the lowest date
i read the excel sheet and put it in datatable :
i tried this code :
protected void CheckTheFP(DataTable data)
{
if (data.Rows.Count != 0)
{
DateTime ds = new DateTime();
err.Text = DateTime.TryParseExact(data.Rows[0][2].ToString(), "MM/dd/yy hh:mm tt",
CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
out ds) + "" ;
}
}
but i always get false ... don't know why ?
and is there a way to sort this datatable or take the highest and lowest date
this the excel sheet i read from
This format string should work: "M/dd/yy h:mm tt". I've used single M because the month has one digit, the same applies to the hours. I've used CultureInfo.InvariantCulture to prevent that all / will be replaced with your actual date-separator (in case that it's different).
You can use LINQ:
var allDateTimes = data.AsEnumerable()
.Select(row => DateTime.ParseExact(row.Field<string>("Time"), "M/dd/yy h:mm tt", CultureInfo.InvariantCulture));
DateTime min = allDateTimes.Min();
DateTime max = allDateTimes.Max();
If you want to be on the safe side you should use TryParseExact, for example with this code:
IEnumerable<DateTime> allDateTimes = data.AsEnumerable()
.Select(row => {
string time = row.Field<string>("Time").Trim();
DateTime dt;
if (DateTime.TryParseExact(time, "M/dd/yy h:mm tt", CultureInfo.InvariantCulture, DateTimeStyles.None, out dt))
return (DateTime?) dt;
return null; // set a breakpoint here to see which value could not be parsed
})
.Where(dt => dt.HasValue)
.Select(dt => dt.Value);
DateTime min = allDateTimes.Min();
DateTime max = allDateTimes.Max();
Edit: you: "when i try to use it on the date 11/2/14 4:42 PM you see the 11 is not in M datetime format
The month is not the problem. Use single d instead because the days can have a single digit also.
So: "M/d/yy h:mm tt"

Getting valid Datetime such as Month/day/year format

my string is like this "21.05.2013 00:00:00"
but i want like this : "05/21/2013";
so i used format
String.Format("{0:M d yy}", myObject.StartAt.ToString());
but instead of this "05/21/2013" it produce this
"05.21.2013 00:00:00"
Edited area ----------
i tried below code but it still give wrong format it still give "05.20.2013" instead of "05/20/2013";
DateTime arrivalDate = DateTime.ParseExact(hotelSearchModel.StartAt.ToString(), "dd.MM.yyyy hh:mm:ss", CultureInfo.InvariantCulture);
DateTime departureDate = DateTime.ParseExact(hotelSearchModel.StartAt.ToString(), "dd.MM.yyyy hh:mm:ss", CultureInfo.InvariantCulture);
request.arrivalDate = arrivalDate.ToString("MM/dd/yyyy");
request.departureDate = departureDate.ToString("MM/dd/yyyy");
Is StartAt a string or a DateTime? If it's a string, you'll need to convert it to DateTime for the formatting to work. Also, you'll need to change your formatting pattern to MM/dd/yyyy to get 05/21/2013:
DateTime dt = DateTime.ParseExact(myObject.StartAt, "dd.MM.yyyy hh:mm:ss", CultureInfo.InvariantCulture);
string s = dt.ToString("MM/dd/yyyy");

String was not recognized as a valid DateTime

I am getting this error: String was not recognized as a valid DateTime.
DateTime date = DateTime.ParseExact("4/29/2013", "MM/dd/yyyy", null);
Use one M instead of MM to match the format for months values that are one or two numbers.
The same goes for d for days.
DateTime date = DateTime.ParseExact("4/29/2013", "M/dd/yyyy", null);
DateTime aDate = DateTime.ParseExact("4/2/2013", "M/d/yyyy", null);

string variable date to double in c#

In the following code ,i need to convert string to double. But the code doesn't work.
string fdate="7/4/2013";
double nextdate = Convert.ToDouble( fdate);
Try this..
DateTime ddd=Convert.ToDateTime("7/4/2013");
double dd = Convert.ToDouble(Convert.ToString(ddd.Month) + Convert.ToString(ddd.Day) + Convert.ToString(ddd.Year));
It will surely work
First convert date string you have to date using DateTime.ParseExact and use it to Convert.ToDouble or DateTime.ToOADate to convert it to double.
string fdate = "7/4/2013";
DateTime date = DateTime.ParseExact(fdate, "d/m/yyyy", System.Globalization.CultureInfo.InvariantCulture);
double nextdate = date.ToOADate();

Resources