I have data from database "192624". how I can change the String format in flutter become time formatted. example "192624" become to "19:26:24". I try using intl packages is not my hope result.
this my code
DateTime inputDate = inputDate;
String formattedTime = DateFormat.Hms().format(inputDate);
in above is not working
I want result convert data("192624") to become "19:26:24". data time from database.
use this method
String a() {
var a = "192624".replaceAllMapped(
RegExp(r".{2}"), (match) => "${match.group(0)}:");
var index = a.lastIndexOf(":");
a = a.substring(0,index);
return a;
}
Have you checked out this a answer :
String time;
// call this upper value globally
String x = "192624";
print(x.length);
x = x.substring(0, 2) + ":" + x.substring(2, 4)+":"+x.substring(4,x.length);
time =x;
print(x);
just globally declare the string and then assign the local String to global then call it in the ui
Related
I have to check runtime Type of value for this I am using :-
for Example:-
String a = "abc";
int b = 123;
var c = "123"; //this is int value but because of this double quotes is represent as a String
a.runtimeType == String //true
b.runtimeType == int // true
c.runtimeType == String //true
c.runtimeType == int //false
a = "abc" // okay
b = 123 //okay
c = "123" //is issue
now I have to call a api with only String body in this case :-
this c is called the API because is String but i know this is a int value which is present as a String, so I have to stop this.
How can I check this??
when I am using try catch so my program is stopped because of FormatException error.
Note:- I don't know the real value of C, may be its "123" or "65dev" or "strjf" this value is changed every time.
and if i am parsing this in int to this return an error in many case.
Ok i understood that you want to pass "123" by checking and if it is int you are passing it , My question is what you will do if it is "123fe" you are going to pass as string? or you will pass nothing.
I don't know how you're passing it to API but if you wanna pass integer value from string quoted variable, you can parse/convert to integer like this.
int.parse(c);
either you can pass it directly or you can store in another variable and pass that variable.
Alternatively if you've int value and to have to pass it as a string, simply parse like this
integerValue.toString();
according to your code
b.toString();
Edit
String a = '20';
String b = 'a20';
try{
int check = int.parse(a);
//call your api inside try then inside if
if(check.runtimeType == int){
print('parsed $check');
}
}
catch(e){
print('not parsed ');
//handle your error
throw(e);
}
This will definitely help you!
String name = "5Syed8Ibrahim";
final RegExp nameRegExp = RegExp(r'^[a-zA-Z ][a-zA-Z ]*[a-zA-Z ]$');
print(nameRegExp.hasMatch(name));
//output false
name = "syed ibrahim";
print(nameRegExp.hasMatch(name));
//output true
Just check the output and based on that boolean value invoke api call
I hope it will done the work
I want to subtract two different times in flutter for example
String time1 = "07:00";
String time2 = "08:12";
String time3 = time2 - time1;
//result will be 01:12
this is just a sample data explanation of what I want to achieve.
See the sample code below. It prints 01:12 in the end.
Input Data:
String time1 = "07:00";
String time2 = "08:12";
Required Methods to be defined:
DateTime getTime(final String inputString) => DateFormat("hh:mm").parse(inputString);
String getString(final Duration duration) {
String formatDigits(int n) => n.toString().padLeft(2, '0');
final String minutes = formatDigits(duration.inMinutes.remainder(60));
return "${formatDigits(duration.inHours)}:$minutes";
}
Computation
final String difference = getString(getTime(time2).difference(getTime(time1)));
Printing the result
print(difference); // 01:12
Have fun - but keep in mind to change the naming of the methods to better fit into your context.
You should use Dart's built-in DateTime class and its DateTime.parse especially.
Documentation: https://api.dart.dev/stable/2.8.4/dart-core/DateTime/parse.html
Try out below code for get difference between two times.
var timeFormat = DateFormat("HH:mm"); //Time format
var first = timeFormat.parse("10:40");
var second = timeFormat.parse("18:20");
print("Difference -->${second.difference(first)}");
// prints Difference -->7:40
Flutter|Dart provides a data type to handle dates : DateTime. So instead of using String, use DateTime :
DateTime time1 = DateTime.parse(your_date_here your_time);
DateTime time2 = DateTime.parse(your_date_here your_time);
DateTime time3 = time2.difference(time1);
If you want just the time part, you can format it using DateFormat from the intl package. You'll need to import it as follows :
import 'package:intl/intl.dart';
Then do the following:
String formattedTime = DateFormat.Hms().format(time1);
String formattedTime = DateFormat.Hms().format(time2);
Or you can just directly format the result (time3):
String formattedTime = DateFormat.Hms().format(time3);
I guess it is not possible to parse a date in "MMddyy" format in dart.
void main() {
String strcandidate = "031623";
String format = "MMddyy";
var originalFormat = DateFormat(format).parse(strcandidate);
}
Output:
Uncaught Error: FormatException: Trying to read dd from 031623 at position 6
The following works fine when parsing a date in "MM-dd-yy" format.
void main() {
String strcandidate = "03-16-23";
String format = "MM-dd-yy";
var originalFormat = DateFormat(format).parse(strcandidate);
}
In the problem, the input date string can be in any format e.g ['yyyy-MM-dd', 'MMM'-yyyy, 'MM/dd/yy']. I am parsing the input string for these formats in a loop as follows.
dateFormatsList = ['yyyy-MM-dd', 'MMM'-yyyy, 'MM/dd/yy'];
for (String format in dateFormatsList ) {
try {
originalFormat = DateFormat(format).parse(strcandidate);
dateFound = true;
} catch (e) {}
}
Adding 'MMddyy' to dateFormatsList is not going to work.
But regular expression be used to parse this format.
However if all formats are parsed using parse method and one additional format is parsed using regular expression, then the code is not that neat, and cluttered.
To write as much neat and efficient code as possible, if you want, you can share your insights about any possibility for making it efficient and clean while incorporating 'MMddyy'format. Tysm!
See How do I convert a date/time string to a DateTime object in Dart? for how to parse various date/time strings to DateTime objects.
If you need to mix approaches, you can provide a unified interface. Instead of using a List<String> for your list of formats, you can use a List<DateTime Function(String)>:
import 'package:intl/intl.dart';
/// Parses a [DateTime] from [dateTimeString] using a [RegExp].
///
/// [re] must have named groups with names `year`, `month`, and `day`.
DateTime parseDateFromRegExp(RegExp re, String dateTimeString) {
var match = re.firstMatch(dateTimeString);
if (match == null) {
throw FormatException('Failed to parse: $dateTimeString');
}
var year = match.namedGroup('year');
var month = match.namedGroup('month');
var day = match.namedGroup('day');
if (year == null || month == null || day == null) {
throw ArgumentError('Regular expression is malformed');
}
// In case we're parsing a two-digit year format, instead of
// parsing the strings ourselves, reparse it with [DateFormat] so that it can
// apply its -80/+20 rule.
//
// [DateFormat.parse] doesn't work without separators, which is why we
// can't use directly on the original string. See:
// https://github.com/dart-lang/intl/issues/210
return DateFormat('yy-MM-dd').parse('$year-$month-$day');
}
typedef DateParser = DateTime Function(String);
DateParser dateParserFromRegExp(String rePattern) =>
(string) => parseDateFromRegExp(RegExp(rePattern), string);
var parserList = [
DateFormat('yyyy-MM-dd').parse,
DateFormat('MMM-yyyy').parse,
DateFormat('MM/dd/yy').parse,
dateParserFromRegExp(
r'^(?<month>\d{2})(?<day>\d{2})(?<year>\d{4})$',
)
];
void main() {
var strcandidate = '12311776';
DateTime? originalFormat;
for (var tryParse in parserList) {
try {
originalFormat = tryParse(strcandidate);
break;
} on Exception {
// Try the next format.
}
}
print(originalFormat);
}
I think it's a bit hacky but what about use a regular expression (RegExp) to parse the date divider and then replace it with just ""?
void main() {
String strcandidate = "031623";
String strYear = strcandidate.substring(4);
//Taken 20 as the year like 2023 as year is in 2 digits
String _newDateTime = '20' + strYear + strcandidate.substring(0, 4);
var _originalFormat = DateTime.parse(_newDateTime);
print(_originalFormat);
}
add the intl to yaml then write this code:
import 'package:intl/intl.dart';
void main() {
var strcandidate = DateTime(2023, 3, 16);
String format = "MMddyy";
var originalFormat = DateFormat(format).format(strcandidate);
print(originalFormat);
}
Dart/Flutter - How to avoid auto rounding done by NumberFormat.compactCurrency(locale: "en_IN").format() method while formatting a value?
num value = 29886964;
NumberFormat numberFormat = NumberFormat.compactCurrency(locale: "en_IN");
String output = numberFormat.format(value);
Actual output = INR2.99Cr
Requirement/Expectation: INR2.98Cr
use NumberFormat.currency api
num value = 29886964;
NumberFormat numberFormat = NumberFormat.compactCurrency(locale: "en_IN" );
final count = math.pow(10 , (value.toString().length - numberFormat.significantDigits));
var result = value / count;
String output = numberFormat.format(result.floor() * count);
print(output);
value : INR2.98Cr
The Accepted answer didn't work for me, unfortunately.
So, this is my answer.
extension DoubleExtension on double {
String get formattedCurrency {
final formatter = NumberFormat.currency(symbol: '\$', decimalDigits: 2);
return formatter.format(this);
}
// Another way around
String get formattedCurrency_2 {
final formatter = NumberFormat('###.0#');
return formatter.format(this);
}
}
and you can use the extension this way:
<your_double_number>.formattedCurrency;
Don't forget to import the extension in your class.
For more info about the configuration please look at this document:
https://api.flutter.dev/flutter/intl/NumberFormat-class.html
I have been given some file name which can be like
<filename>YYYYMMDD<fileextension>
some valid file names that will satisfy the above pattern are as under
xxx20100326.xls,
xxx2v20100326.csv,
x_20100326.xls,
xy2z_abc_20100326_xyz.csv,
abc.xyz.20100326.doc,
ab2.v.20100326.doc,
abc.v.20100326_xyz.xls
In what ever be the above defined case, I need to pick up the dates only. So for all the cases, the output will be 20100326.
I am trying to achieve the same but no luck.
Here is what I have done so far
string testdata = "x2v20100326.csv";
string strYYYY = #"\d{4}";
string strMM = #"(1[0-2]|0[1-9])";
string strDD = #"(3[0-1]|[1-2][0-9]|0[1-9])";
string regExPattern = #"\A" + strYYYY + strMM + strDD + #"\Z";
Regex regex = new Regex(regExPattern);
Match match = regex.Match(testdata);
if (match.Success)
{
string result = match.Groups[0].Value;
}
I am using c#3.0 and dotnet framework 3.5
Please help. It is very urgent
Thanks in advance.
Try this:
DateTime result = DateTime.MinValue;
System.Globalization.CultureInfo provider = System.Globalization.CultureInfo.InvariantCulture;
var testString = "x2v20100326.csv";
var format = "yyyyMMdd";
try
{
for (int i = 0; i < testString.Length - format.Length; i++)
{
if (DateTime.TryParseExact(testString.Substring(i, format.Length), format, provider, System.Globalization.DateTimeStyles.None, out result))
{
Console.WriteLine("{0} converts to {1}.", testString, result.ToString());
break;
}
}
}
catch (FormatException)
{
Console.WriteLine("{0} is not in the correct format.", testString);
}
This one fetches the last date in the string.
var re = new Regex("(?<date>[0-9]{8})");
var test = "asdf_wef_20100615_sdf.csv";
var datevalue = re.Match(test).Groups["date"].Value;
Console.WriteLine(datevalue); // prints 20100615
Characters \A and \Z - begin and end of the string respectivly.
I think you need pattern like:
string regExPattern = #"\A.*(?<FullDate>" + strYYYY + strMM + strDD + #").*\..*\Z";
".*" - any symbols at the begin
".*\..*" - any symbols before the dot, dot and any symbols after dot
And get a full date:
match.Groups["FullDate"]
You may need to group things in your month and day expressions:
((1[0-2])|(0[1-9))
((3[0-1])|([1-2][0-9])|(0[1-9]))