Parse several formats' date in Java 8 - date

I need to convert a date from a old format to a new format in Java 8, there are several old formats, so it converts the date with the first matched format. How can I do it? Thanks a lot.
String oldFormat1 = "MM/dd/yyyy HH:mm:ss a";
String oldFormat2 = "dd/MM/yyyy HH:mm:ss";
String newFormat = "dd/MM/yyyy";
try {
SimpleDateFormat format = new SimpleDateFormat(oldFormat1);
Date date = format.parse(dateStr);
format.applyPattern(newFormat);
String newDateString = format.format(date);
return source;
} catch (ParseException e) {
SimpleDateFormat format = new SimpleDateFormat(oldFormat2);
Date date = format.parse(dateStr);
format.applyPattern(newFormat);
String newDateString = format.format(date);
return source;
...
}
Solution
As mentioned below, I used DateTimeFormatter and LocalDateTime to realize the function.
DateTimeFormatter formatter = new DateTimeFormatterBuilder()
.appendOptional(DateTimeFormatter.ofPattern(oldFormat1))
.appendOptional(DateTimeFormatter.ofPattern(oldFormat2))
.toFormatter();
DateTimeFormatter newFormatter = DateTimeFormatter.ofPattern(newFormat);
try {
LocalDateTime dateTime = LocalDateTime.parse(dateStr, formatter);
String source = newFormatter.format(dateTime);
return " - " + source;
} catch (NullPointerException e) {
log.error("Wrong date: {}", dateStr);
}

Related

Dart Flutter - How do I combine & convert separated date & time into one DateTime object

String oldDateStr = "2022-08-1";
String oldTimeStr = "03:10 pm";
DateTime? newDateTime; //2022-08-01 13:10 (yyyy-MM-dd HH:mm) <----- TARGET
final olddateFormat = DateFormat("yyyy-MM-d");
final newdateFormat = DateFormat("yyyy-MM-dd");
final oldtimeFormat = DateFormat("hh:mm a");
final timeFormatter = DateFormat("HH:mm");
DateTime oldTime12 = oldtimeFormat.parse(oldTimeStr.toUpperCase());
DateTime newTime24 = DateTime.parse(timeFormatter.format(oldTime12)); //This line is culprit in print() debug
DateTime oldDate = olddateFormat.parse(oldDateStr);
DateTime newDate = DateTime.parse(newdateFormat.format(oldDate));
I tried & combined various answers from SO posts but couldn't figure this out. So I'm posting the question by helplessness.
The accepted format is yyyy-MM-dd hh:mm aaa. am/pm marker assumes capital letters e.g PM.
import 'package:intl/intl.dart';
void main() {
String oldDateStr = "2022-08-1";
String oldTimeStr = "03:10 pm";
final result = DateFormat("yyyy-MM-dd hh:mm aaa").parse(
'$oldDateStr $oldTimeStr'.replaceAll('pm', 'PM').replaceAll('am', 'AM'),
);
print(result); // 2022-08-01 15:10:00.000
}
See DateFormat for more information.
You can get formatted date like this, make a function if you are using it frequently.
String oldDateStr = "2022-08-01";
String oldTimeStr = "03:10 pm";
DateTime? newDateTime;
String newDate = (oldDateStr + " "+oldTimeStr.substring(0, 5) + ":00.000");
DateFormat formatter = DateFormat ('yyyy-MM-dd hh:mm');
DateTime nt = DateTime.parse(newDate);
print(formatter.format(nt));
use this package to combine date and time and convert your datetime format to DateTime
String oldDateStr = "2022-08-1";
String oldTimeStr = "03:10 pm";
final String dateTimeString = oldDateStr+ " " + oldTimeStr;
final DateFormat format = new DateFormat("yyyy-MM-dd hh:mm a");
print (format.parse(dateTimeString));

How to convert a simple string to a DateTime object?

I am tring to convert a simple string into a date time but it is showing invalid exception. Here's the code :
void main() {
String date = '12';
date = DateTime.parse(date).toString();
print(date);
}
Can anyone help ?
Your date string is not valid.
Here is example of it:
String time = '2022-01-13';
DateTime parseDate = DateFormat("yyyy-MM-dd").parse(time); // to be date
var inputDate = DateTime.parse(parseDate.toString()); // to be string
var outputFormat = DateFormat('dd MMM yyyy'); // set format be for ex 13 Jan 2022
var outputDate = outputFormat.format(inputDate); // set to be a string
While it doesn't make much sense in this form, it will work:
import 'package:intl/intl.dart';
void main() {
String date = '12';
DateTime dateTime = DateFormat("MM").parse(date);
print(dateTime);
}

Can't convert a Datetime from a string to another format (eg: 14/12/2021 03:34:03 PM to 03:34 pm)

I'am trying to convert a datetime string from one format to another. i tried to use intl package. But i don't know how to convert this string to another format.
The datetime string i'am getting from api is 14/12/2021 03:34:03 PM. I want to show it like this in my app (only time) 03:34 pm (Also want to make PM Small letter).
Try below code hope its helpful to you. I have tried it without using any third party library
String yourDate = '14/12/2021 03:34:03 PM';
DateFormat formateDate = DateFormat('dd/MM/yyyy hh:mm:ss a');
DateTime inputDate = formateDate.parse(yourDate);
String resultDate = DateFormat('hh:mm a').format(inputDate);
print(resultDate.toLowerCase());
Your Widget:
Text(
'Time : ${resultDate.toLowerCase()}',
style: TextStyle(
fontSize: 15,
),
),
Your Result Screen->
If you don't mind doing it the regexp way
import 'package:intl/intl.dart';
void main() {
var s = "14/12/2021 12:34:03 PM";
print(formatDateTimeString(s));
}
String formatDateTimeString(String s) {
RegExp regexp = RegExp("(AM|PM)");
// finds either AM or PM in string and converts it to lowercase
RegExpMatch match = regexp.firstMatch(s)!;
String end = match.group(0)!.toLowerCase();
// change datetime format to HH:mm as desired
DateTime dt = DateFormat("d/MM/yyyy HH:mm:ss").parse(s);
DateFormat newFormat = DateFormat("HH:mm");
String formattedS = newFormat.format(dt);
// append lowercase ampm
formattedS += " " + end;
return formattedS;
}
You can get it by using below,
dateFormat() {
String dateStart = '14/12/2021 03:34:03 PM';
DateFormat inputFormat = DateFormat("dd/MM/yyyy hh:mm:ss a");
DateTime input = inputFormat.parse(dateStart);
String dateOutput = DateFormat("hh:mm a").format(input);
return dateOutput.toLowerCase();
}
String formattedDate = DateFormat('yyyy-MM-dd – kk:mm').format(now);
How to format DateTime in Flutter
please check out, it's for all formated datetime , you just pass your current and required date format
import 'package:intl/intl.dart';
void main() {
var data = "14/12/2021 03:34:03 PM";
print(getFormattedDateFromFormattedString(
value: data,
currentFormat: "yyyy/MM/dd HH:mm:ss a",
desiredFormat: "hh:mm a").toLowerCase()); //03:34 pm
}
String getFormattedDateFromFormattedString(
{required value,
required String currentFormat,
required String desiredFormat,
isUtc = false}) {
String formattedDate = "";
if (value != null || value.isNotEmpty) {
try {
DateTime dateTime =
DateFormat(currentFormat).parse(value, isUtc).toLocal();
formattedDate = DateFormat(desiredFormat).format(dateTime);
} catch (e) {
print("$e");
}
}
// print("Formatted date time: $formattedDate");
return formattedDate;
}

Flutter DateFormat Invalid date format

I have a string like this String dt = '04-09-2021 - 15:00'
i want to convert it into local time zone
and my code is:
if(dt != 'Not Available'){
return DateFormat('dd-MM-yyyy - HH:mm')
.format(DateTime.parse(dt).toLocal())
.toString();
}else{
return dt;
}
But i get the error: Invalid date format 04-09-2021 - 15:00
You should use parse, not format, the format functions receive a date, but you don't have a date, you have an string, use:
DateFormat('dd-MM-yyyy - HH:mm').parse(dt);
Here I wrote a dateformatter and convert it to local time. As well as you can format like as you wish.
// call getFormattedDateFromFormattedString function in Text
Center(
child: Text(getFormattedDateFromFormattedString(
currentFormat: "dd-MM-yyyy - HH:mm",
desiredFormat: "dd MMM yyyy HH:mm a",
value: "04-09-2000 - 15:00")),
)
// date fomatter function
String getFormattedDateFromFormattedString(
{#required String currentFormat,
#required String desiredFormat,
String value}) {
String formattedDate = "";
if (value != null || value.isNotEmpty) {
try {
DateTime dateTime = DateFormat(currentFormat).parse(value, true).toLocal();
formattedDate = DateFormat(desiredFormat).format(dateTime);
} catch (e) {
print("$e");
}
}
// print("Formatted date time: $formattedDate");
return formattedDate.toString();
}
Output:
N.B: My time zone GMT+6.0

How to convert a date from format MM/dd/yyyy to Julian format CCYYDDD?

I have the following function "Format" to convert a date from the format "MM/dd/yyyy" to MMddyyyy.
This function works with the below data but would not work if I want to convert a date from "MM/dd/yyyy" to CCYYDDD. What should be done in this function to support Julian date conversion? Thanks for any help!
string Value = "03/11/2011";
string formatType = "System.DateTime";
string outputformat = "MMddyyyy";
Value = Format(formatType, Value, outputformat);
private static string Format(string typename, string value, string format)
{
Type t = Type.GetType(typename);
System.Reflection.MethodInfo infoParse = t.GetMethod("Parse", new Type[] { typeof(string) });
object o = infoParse.Invoke(null, new object[] { value });
System.Reflection.MethodInfo infoToString = t.GetMethod("ToString", new Type[] { typeof(string) });
return infoToString.Invoke(o, new object[] { format }) as string;
}
Use the output format "yyyyddd".