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

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;
}

Related

Dart - Convert time from dd/MM/YYYY to YYYY-MM-dd

How to convert a date from dd/MM/YYYY to YYYY-MM-dd
Example: convert from 08/11/2019 to 2019-11-08
I tried the following code but got the
Invalid date format 08/11/2019 exception
import 'package:intl/intl.dart';
DateFormat('YYYY-MM-dd').format(DateTime.parse('08.11.2019'));
var inputFormat = DateFormat('dd/MM/yyyy');
var date1 = inputFormat.parse('18/08/2019');
var outputFormat = DateFormat('yyyy-MM-dd');
var date2 = outputFormat.format(date1); // 2019-08-18
Or you can use String
var date2String = outputFormat.format(date1); // "2019-08-18"
Try using this package, Jiffy. It is inspired by momentjs.
This can be solved in one line
var dateTime = Jiffy("18/08/2019", "dd/MM/yyyy").format("yyyy-MM-dd"); // 2019-08-18
You can also format it with default formats
var dateTime = Jiffy("18/08/2019", "dd/MM/yyyy").yMMMMd; // August 18, 2019

Parsing time string in java 8 - Invalid value for ClockHourOfAmPm [duplicate]

This question already has answers here:
How to set 24-hours format for date on java?
(10 answers)
Closed 3 years ago.
I am trying to convert time zones with given time in my properties file.
package test1;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimeZoneConversion {
private static final String DATE_FORMAT = "yyyy-MM-dd-hh-mm-ss";
public static void main(String[] args) {
String ds = "2019-03-18 13-14-48";
LocalDateTime ldt = LocalDateTime.parse(ds, DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println("ldt : "+ldt);
ZoneId singaporeZoneId = ZoneId.of("Asia/Singapore");
System.out.println("TimeZone : " + singaporeZoneId);
//LocalDateTime + ZoneId = ZonedDateTime
ZonedDateTime asiaZonedDateTime = ldt.atZone(singaporeZoneId);
System.out.println("Date (Singapore) : " + asiaZonedDateTime);
ZoneId newYokZoneId = ZoneId.of("America/New_York");
System.out.println("TimeZone : " + newYokZoneId);
ZonedDateTime nyDateTime = asiaZonedDateTime.withZoneSameInstant(newYokZoneId);
System.out.println("Date (New York) : " + nyDateTime);
DateTimeFormatter format = DateTimeFormatter.ofPattern(DATE_FORMAT);
System.out.println("\n---DateTimeFormatter---");
System.out.println("Date (Singapore) : " + format.format(asiaZonedDateTime));
System.out.println("Date (New York) : " + format.format(nyDateTime));
}
}
SO I am getting error :
Exception in thread "main" java.time.format.DateTimeParseException: Text '2019-03-18 13-14-48' could not be parsed: Invalid value for ClockHourOfAmPm (valid values 1 - 12): 13
at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
at java.time.LocalDateTime.parse(LocalDateTime.java:492)
at test1.FirstClass.main(FirstClass.java:20)
I do not have AM/PM value in the date time that I getting from properties file. This value is stored in String ds. in the above code I have hardcoded it. How does it work? How to make it work with the time date format which I have given?
You should change the DATE_FORMAT to:
private static final String DATE_FORMAT = "yyyy-MM-dd HH-mm-ss";
If you refer the DateTimeFormatter docs you see the description as follows:
H hour-of-day (0-23)
In your case you are supplying the hour as the hour-of-day (HH) instead of in clock-hour-of-am-pm (hh a) format from your properties file. And as 13 ( > 12) is not an acceptable value for clock-hour-of-am-pm without the AM/PM you are getting an exception.
If you want it in clock-hour-of-am-pm you need to change the format to:
private static final String DATE_FORMAT = "yyyy-MM-dd hh-mm-ss a";
And also add the AM/PM information in the date string:
String ds = "2019-03-18 12-14-48 AM";

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"

How to convert date string to specific date format?

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...

Convert date time format from dd/MM/yyyy to MM/dd/yyyy [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Convert dd-mm-yyyy into mm/dd/yyyyy in C#
I want to Convert Date time format from dd/MM/yyyy to MM/dd/yyyy in C#
Is there any suggestion how to do that?
Please try:
string oldstr = "03/12/2011";
string strDate = DateTime.ParseExact(oldstr, "dd/MM/yyyy",null).ToString("MM/dd/yyyy");
Console.WriteLine(strDate);
DateTimeFormatInfo usDtfi = new CultureInfo("en-US", false).DateTimeFormat; //--MM/dd/yyyy
DateTimeFormatInfo ukDtfi = new CultureInfo("en-GB", false).DateTimeFormat; //--dd/MM/yyyy
DateTime result = Convert.ToDateTime("07/21/2011", usDtfi); //or: ("21/07/2011", ukDtfi)
Then you have a DateTime Object (result) and do whatever you want like:
string str = result.ToString("yyyy-MM-dd HH:mm:ss");
Happy Coding :)
try this
string DateString = "22/04/2011";
DateTime date = new DateTime();
date = DateTime.ParseExact(DateString, "dd/MM/yyyy");
string NewDateString = date.ToString("MM/dd/yyyy");

Resources