How to convert the time to am/pm ?
I have this output
I/flutter (17720): 9:00:00
I/flutter (17720): 11:00:00
I/flutter (17720): 12:00:00
This is what I have tried
final item = snapshot.data[index];
print("Time " + item['time'].toString());
DateTime dateTime = DateTime.parse(item['time'].toString());
print(DateUtil().formattedTime(dateTime));
DateUtil
String formattedTime(DateTime dateTime) {
return DateFormat().add_jm().format(dateTime);
}
Error
I/flutter (17720): Time 09:00:00
════════ Exception caught by widgets library
═══════════════════════════════════ The following FormatException was
thrown building Tags(dirty, state: TagsState#b3a2f): Invalid date
format 09:00:00
Use this code:
DateFormat('hh:mm a').format(DateTime.now());
According to the intl library, it states that a represents AM/PM.
You can use the intl library https://pub.dev/packages/intl
and format your DateTime
DateFormat.yMEd().add_jms().format(DateTime.now());
Output:
'Thu, 5/23/2013 10:21:47 AM'
DateFormat class
DateFormat is for formatting and parsing dates in a locale-sensitive manner.
Convert Time
print(DateFormat.jm().format(DateFormat("hh:mm:ss").parse("14:15:00")));
Output : 3:20 AM
Convert Date
print(DateFormat('yyyy-MMMM-dd').format("2021-05-14 00:00:00.000"));
Output : 2021-May-14
EXAMPLE :
Time Picker
Future<Null> _selectTime(BuildContext context) async {
final TimeOfDay picked = await showTimePicker(
context: context,
initialTime: _con.selectedTime,
);
if (picked != null) {
String selTime =
picked.hour.toString() + ':' + picked.minute.toString() + ':00';
print(DateFormat.jm().format(DateFormat("hh:mm:ss").parse(selTime)));
}}
Date Picker
_selectDate(BuildContext context) async {
final DateTime picked = await showDatePicker(
context: context,
initialDate: _con.selectDateAndTime,
firstDate: DateTime(2021),
lastDate: DateTime(2040),
);
if (picked != null) {
print(picked);
}}
this function can helps to convert only time, Without date
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
String formatedTime(TimeOfDay selectedTime) {
DateTime tempDate = DateFormat.Hms().parse(selectedTime.hour.toString() +
":" +
selectedTime.minute.toString() +
":" +
'0' +
":" +
'0');
var dateFormat = DateFormat("h:mm a");
return (dateFormat.format(tempDate));
}
Here is my solution a little simpler to understand I guess. And there is no need to add any library.
String getFormattedDateTime({d = "2022-11-15 14:21:37.152"}){
List<String> months = [
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
];
List<String> days = [
'Monday',
'Tuseday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday',
];
final dateTimeObj = DateTime.parse(d);
// date format
String fdate = "${days[dateTimeObj.weekday - 1].substring(0, 3)}, ${months[dateTimeObj.month-1].substring(0, 3)}-${dateTimeObj.day}";
// time format
String time = "${(dateTimeObj.hour > 12 ? dateTimeObj.hour - 12 : dateTimeObj.hour).abs()}:${dateTimeObj.minute} ${dateTimeObj.hour >= 12 ? "PM" : "AM"}";
return "$fdate $time";
}
This function will return formatted String something like this Tus, Nov-15 4:54 PM again you can format it accordingly.
Related
I want to add offset GMT +05:30 to Time but I don't know how to do that
String offset = data ['utc_offset'].substring(1,);
ntime =ntime.add(Duration(hours:int.parse(offset)));
Since there is " : " in the middle of 05:30 I can't add the exact value..
PS: I'm using http://worldtimeapi.org JSON API
You can parse the offset time by using a RegExp. I have used named groups in my example since I finds it more simple to understand what each part of the regexp are extracting:
import 'dart:io';
void main() {
const offset = '+01:00';
final regexp =
RegExp(r'^(?<plusMinus>[+-]?)(?<hours>[\d]+):(?<minutes>[\d]+)');
final match = regexp.firstMatch(offset);
print(match.namedGroup('plusMinus'));
print(match.namedGroup('hours'));
print(match.namedGroup('minutes'));
final offsetDuration = Duration(
hours: int.parse(match.namedGroup('hours')),
minutes: int.parse(match.namedGroup('minutes')));
DateTime time;
if (match.namedGroup('plusMinus') == '+') {
time = DateTime.now().add(offsetDuration);
} else if (match.namedGroup('plusMinus') == '-') {
time = DateTime.now().subtract(offsetDuration);
} else {
time = DateTime.now();
}
print(time);
}
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;
}
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
If you pass a non-existing/non-real date like: '20181364' (2018/13/64) into DateTime (constructor or parse-method), no exception is thrown. Instead a calculated DateTime is returned.
Example:
'20181364' --> 2019-03-05 00:00:00.000
How can I check if a given date really exists/is valid?
I tried to solve this using DartPad (without success), so no Flutter doctor output required here.
void main() {
var inputs = ['20180101', // -> 2018-01-01 00:00:00.000
'20181231', // -> 2018-12-31 00:00:00.000
'20180230', // -> 2018-03-02 00:00:00.000
'20181301', // -> 2019-01-01 00:00:00.000
'20181364'];// -> 2019-03-05 00:00:00.000
inputs.forEach((input) => print(convertToDate(input)));
}
String convertToDate(String input){
return DateTime.parse(input).toString();
}
It would be great if there exist some kind of method to check if a given date really exists/is valid, e.g.:
a validate function in DateTime
another lib that does not use DateTime.parse() for validation
How would you solve this?
You can convert parsed date to string with original format and then compare if it's matching the input.
void main() {
var inputs = ['20180101', // -> 2018-01-01 00:00:00.000
'20181231', // -> 2018-12-31 00:00:00.000
'20180230', // -> 2018-03-02 00:00:00.000
'20181301', // -> 2019-01-01 00:00:00.000
'20181364'];// -> 2019-03-05 00:00:00.000
inputs.forEach((input) {
print("$input is valid string: ${isValidDate(input)}");
});
}
bool isValidDate(String input) {
final date = DateTime.parse(input);
final originalFormatString = toOriginalFormatString(date);
return input == originalFormatString;
}
String toOriginalFormatString(DateTime dateTime) {
final y = dateTime.year.toString().padLeft(4, '0');
final m = dateTime.month.toString().padLeft(2, '0');
final d = dateTime.day.toString().padLeft(2, '0');
return "$y$m$d";
}
My solution to validate the birthday was this, we can see that it has the leap year calculation.
class DateHelper{
/*
* Is valid date and format
*
* Format: dd/MM/yyyy
* valid:
* 01/12/1996
* invalid:
* 01/13/1996
*
* Format: MM/dd/yyyy
* valid:
* 12/01/1996
* invalid
* 13/01/1996
* */
static bool isValidDateBirth(String date, String format) {
try {
int day, month, year;
//Get separator data 10/10/2020, 2020-10-10, 10.10.2020
String separator = RegExp("([-/.])").firstMatch(date).group(0)[0];
//Split by separator [mm, dd, yyyy]
var frSplit = format.split(separator);
//Split by separtor [10, 10, 2020]
var dtSplit = date.split(separator);
for (int i = 0; i < frSplit.length; i++) {
var frm = frSplit[i].toLowerCase();
var vl = dtSplit[i];
if (frm == "dd")
day = int.parse(vl);
else if (frm == "mm")
month = int.parse(vl);
else if (frm == "yyyy")
year = int.parse(vl);
}
//First date check
//The dart does not throw an exception for invalid date.
var now = DateTime.now();
if(month > 12 || month < 1 || day < 1 || day > daysInMonth(month, year) || year < 1810 || (year > now.year && day > now.day && month > now.month))
throw Exception("Date birth invalid.");
return true;
} catch (e) {
return false;
}
}
static int daysInMonth(int month, int year) {
int days = 28 + (month + (month/8).floor()) % 2 + 2 % month + 2 * (1/month).floor();
return (isLeapYear(year) && month == 2)? 29 : days;
}
static bool isLeapYear(int year)
=> (( year % 4 == 0 && year % 100 != 0 ) || year % 400 == 0 );
}
Support for validating dates was added for dart in December 2020: https://pub.dev/documentation/intl/latest/intl/DateFormat/parseStrict.html
I need to get the day, month, year details from a Date value but getYear() is deprecated, gives year on 2 digits, and has problems with Y2K (2008 gives 108). The java doc recommends using java.util.calendar but it is not supported in GWT.
I want to avoid sending all the info back and forth between the server and client just to deal with dates.
Edit: Calendar might be supported Date handling functions should be implemented in GWT futur versions : http://code.google.com/p/google-web-toolkit/issues/detail?id=603
The workaround presented by Ashwin works and it's not that tricky. But I'd suggest using the date patterns instead of splitting:
For date -
DateTimeFormat.getFormat( "d" ).format( new Date() )
For month -
DateTimeFormat.getFormat( "M" ).format( new Date() )
For year -
DateTimeFormat.getFormat( "yyyy" ).format( new Date() )
Do not use those deprecated methods on Date class in GWT.
If you don't want to use third party Date implementations for GWT, You use a combination of DateTimeFormat along with string manipulation as a workaround for the time being, until GWT comes up with some better support for manipulating dates.
For date -
DateTimeFormat.getFormat( "d-M-yyyy" ).format( new Date() ).split( "-")[0]
For month -
DateTimeFormat.getFormat( "d-M-yyyy" ).format( new Date() ).split( "-")[1]
For year -
DateTimeFormat.getFormat( "d-M-yyyy" ).format( new Date() ).split( "-")[2]
Edit-
Similarly, avoid using new Date( yy, mm, dd ) has come inconsistencies depending on the browser and date range.
I have use a simple DateUtil Class to create and parse Date objects in GWT, maybe of some use to you -
(Warning: Very crude, and work in progress)
public class DateUtil
{
private static final String D_M_YYYY = "d-M-yyyy";
private static final String DATE_SEPARATOR = "-";
public static Date getDate( Integer dd, Integer mm, Integer yyyy )
{
if ( dd == null || mm == null || yyyy == null )
return null;
Date retVal = null;
try
{
retVal = DateTimeFormat.getFormat( D_M_YYYY ).parse( dd + DATE_SEPARATOR + mm + DATE_SEPARATOR + yyyy );
}
catch ( Exception e )
{
retVal = null;
}
return retVal;
}
public static String getDayAsString( Date date )
{
return ( date == null ) ? null : DateTimeFormat.getFormat( D_M_YYYY ).format( date ).split( DATE_SEPARATOR )[0];
}
public static String getMonthAsString( Date date )
{
return ( date == null ) ? null : DateTimeFormat.getFormat( D_M_YYYY ).format( date ).split( DATE_SEPARATOR )[1];
}
public static String getYearAsString( Date date )
{
return ( date == null ) ? null : DateTimeFormat.getFormat( D_M_YYYY ).format( date ).split( DATE_SEPARATOR )[2];
}
public static boolean isValidDate( Integer dd, Integer mm, Integer yyyy )
{
boolean isvalidDate = true;
try
{
String transformedInput = DateTimeFormat.getFormat( D_M_YYYY ).format( getDate( dd, mm, yyyy ) );
String originalInput = dd + DATE_SEPARATOR + mm + DATE_SEPARATOR + yyyy;
isvalidDate = transformedInput.equals( originalInput );
}
catch ( Exception e )
{
isvalidDate = false;
}
return isvalidDate;
}
}
You may just add 1900 to getYear() return value
I don't think gwt will support Calendar in the future, may be it could support another date manipulation implementation.
So, because the java recommendation about not using Date is not valid in Gwt and you have not any other option without importing a third party library, the right way is to use Date and ignore deprecation warnings.