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
Related
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;
}
I´m trying to convert a String date like "Thu May 24 2018 14:00:00 GMT+0200" to Joda DateTime (v.2.9.9) but I obtain Invalid format exception:
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
for (int i=0; i < arrayHorarios.length; i++) {
DateTime dateTime = new DateTime();
dateTime = formatter.withOffsetParsed().parseDateTime(arrayHorarios[i]);
}
What am I doing wrong? My goal is to convert all Strings containing dates to Java Dates and then save them into DB... what´s the easiest way to do it? (with or without Joda).
EDIT:
I changed to the correct pattern. Using Java DateFormat was useless too:
ObjectMapper mapper = new ObjectMapper();
String[] arrayHorarios = mapper.readValue(horariosSave, String[].class);
DateFormat df = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss z", Locale.ENGLISH);
//sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
List<Date> hor = new ArrayList<Date>();
Date date = new Date();
try {
for (int i=0; i < arrayHorarios.length; i++) {
// conversión de String a Date de los valores
System.out.println("Horario nº:"+i);
System.out.println("String = "+arrayHorarios[i]);
date = df.parse(arrayHorarios[i]);
System.out.println("Date = " + df.format(date));
hor.add(date);
}
System.out.println("Clases guardadas:"+hor.size());
} catch (Exception e) {
e.printStackTrace();
}
This way I get this exception:
java.text.ParseException: Unparseable date: "Fri May 25 2018 12:00:00 GMT+0200"
at java.text.DateFormat.parse(DateFormat.java:366)
java.time
I wonder if there is a way to do it with Java 8 Util Time.
Of course there is.
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern, Locale.ENGLISH);
String horario = "Thu May 24 2018 14:00:00 GMT+0200";
OffsetDateTime dateTime = OffsetDateTime.parse(horario, formatter);
System.out.println(dateTime);
Prints:
2018-05-24T14:00+02:00
Imports used are:
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
Joda-Time
Not that you’ll regret upgrading to java.time, your Joda-Time code seems to be working too:
String pattern = "EEE MMM dd yyyy HH:mm:ss 'GMT'Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern(pattern);
String horario = "Thu May 24 2018 14:00:00 GMT+0200";
DateTime dateTime = formatter.withOffsetParsed().parseDateTime(horario);
System.out.println(dateTime);
This prints:
2018-05-24T14:00:00.000+02:00
I suspect that your problem may be somewhere else.
PS You may already be aware that the Joda-Time home page says:
Users are now asked to migrate to java.time (JSR-310).
To convert Java Date to Joda DateTime:-
Date date = new Date();
DateTime dateTime = new DateTime(date);
With TimeZone, if required:-
TimeZone timeZone= dateTime.getZone().toTimeZone();
DateTime dateTimeNew = new DateTime(date.getTime(), timeZone);
Date dateTimeZone = dateTime.toDateTimeAtStartOfDay(timeZone).toDate();
I am trying to parse date format '2017-12-18T20:41:06.136Z' into "2017-12-18'T'00:00:00"
Date date = new Date();
def dateformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
dateformat.setTimeZone(TimeZone.getTimeZone(TimeZoneCode));
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate
date1 = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00").parse(currentDate)
log.info "Current Date : " + date1
Error displayed :
java.text.ParseException: Unparseable date: "2017-12-18T20:46:06:234Z" error at line: 16
This line gives error :
date1 = new SimpleDateFormat("yyyy-MM-dd'T'00:00:00").parse(currentDate)
Running Groovy on Java 8 gives you access to the much better Date/Time classes... You can just do:
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
String result = ZonedDateTime.parse("2017-12-18T20:41:06.136Z")
.truncatedTo(ChronoUnit.DAYS)
.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
In order to avoid the mentioned error, use below statement Date.parse(..):
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def dateString = "2017-12-18T20:41:06.136Z"
def date = Date.parse(dateFormat, dateString)
You should be able to achieve what you are trying to using below script.
//Change timezone if needed
def tz = 'IST'
TimeZone.setDefault(TimeZone.getTimeZone(tz))
def dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def dateString = "2017-12-18T20:41:06.136Z"
Calendar calendar = Calendar.getInstance()
calendar.with {
time = Date.parse(dateFormat,dateString)
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
log.info calendar.time.format(dateFormat)
You can quickly try the same online demo
if you need to parse only part of date, use the following syntax:
Date.parse("yyyy-MM-dd'T'HH:mm:ss",'2017-12-18T16:05:58bla-bla')
Trying to add 1 day to the simple date format.
import java.text.SimpleDateFormat
Date date = new Date();
def dateformat = new SimpleDateFormat("YYYY-MM-dd")
def currentDate = dateformat.format(date)
log.info "Current Date : " + currentDate
Date date1 = (Date)dateformat.parse(currentDate);
Calendar c1 = Calendar.getInstance();
c1.setTime(date1);
log info c1.add(Calendar.Date,1);
Error occurred in line :
"log info c1.add(Calendar.Date,1);"
groovy.lang.MissingPropertyException:No such property: info for class: Script16 error at line: 10
Note : The current date should be any date in future and i want to increment by 1 day.
You can use TimeCategory to add the day as shown below:
use(groovy.time.TimeCategory) {
def tomorrow = new Date() + 1.day
log.info tomorrow.format('yyyy-MM-dd')
}
EDIT: based on OP comments
Here is another away which is to add method dynamically, say nextDay() to Date class.
//Define the date format expected
def dateFormat = 'yyyy-MM-dd'
Date.metaClass.nextDay = {
use(groovy.time.TimeCategory) {
def nDay = delegate + 1.day
nDay.format(dateFormat)
}
}
//For any date
def dateString = '2017-12-14'
def date = Date.parse(dateFormat, dateString)
log.info date.nextDay()
//For current date
def date2 = new Date()
log.info date2.nextDay()
You may quickly the same online demo
Well, the error you provide clearly tells you, that you have a syntax error. It says that there is no property info.
This is because you write
log info c1.add(Calendar.Date,1);
instead of
log.info c1.add(Calendar.Date,1);
If you would have used the correct syntax, it would complain that Calendar has no property Date.
So instead of
c1.add(Calendar.Date, 1)
you meant
c1.add(Calendar.DAY_OF_MONTH, 1)
But in Groovy you can even make it easier, using
c1 = c1.next()
Actually in my Flex Application i'm passing Date(in String format) as well as Timezone(String format) convert into Date type but it is not converting Date type ... it is giving null value and my
sample code like this...
var tzDate:String="20012-12-12";
var tzString:String=tzComboBox.selectedItem;//hear value GMT+0530
var startDate:Date = DateField.stringToDate(tzDate+" "+tzString,"YYYY-MM-DD TZD");
Alert.show(startDate);//hear value giving "Null"
The problem is it's not converting Date format...Plz Help me
use parse function and format date before parsing
var tzDate:String="2012-12-12";
var tzString:String="GMT+0530";
var dateformat:DateFormatter = new DateFormatter();
dateformat.formatString = "YYYY/MM/DD";
var dateStr:String = dateformat.format(tzDate) +" "+ tzString;
//dateStr is 2012/12/12 GMT+0530
var startDate:Date = new Date(Date.parse(dateStr));
Alert.show(startDate.toString());
//Show Date of Local time Zone
//Tue Dec 11 21:30:00 GMT+0300 2012
Hopes that Helps