Parse date to "yyyy-MM-dd'T'00:00:00" using Groovy - datetime

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')

Related

Date and Time in Kotlin

I am new to kotlin. And I got a problem.
I have this code:
val sdf = SimpleDateFormat("dd.MM.yyyy")
val currentDate = sdf.format(Date())
println(currentDate)
val stringDate = "12.03.2015"
val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)
val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli()
println(millisecondsSinceEpoch)
val time = currentDate - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
But on the line:
val time = currentDate - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
I get the error:
java.lang.IllegalArgumentException: Cannot format given Object as a Date
Please help me how you can fix this. I need to subtract the current date from the date that is in string.
UPDATE:
How to subtract one date from another correctly and get the difference in days?
I suggest you switch from the outdated java.util date/time API to the modern date/time API. Given below is the Java code for your requirement and I hope you should be able to convert the same into Kotlin. However, if you face any issue, I can convert the same into Kotlin code for you.
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH);
// Given date-time
ZonedDateTime givenDateTime = LocalDateTime.of(LocalDate.parse("12.03.2015", formatter), LocalTime.of(0, 0))
.atZone(ZoneId.of("Etc/UTC"));
// Now
ZonedDateTime zdtNow = ZonedDateTime.now(ZoneId.of("Etc/UTC"));
// Period between the two dates
Period period = Period.between(givenDateTime.toLocalDate(), zdtNow.toLocalDate());
// Given date-time with current year, month and day
ZonedDateTime adjusted = givenDateTime.with(LocalDate.now(ZoneId.of("Etc/UTC")));
// Duration between the two times
Duration duration = Duration.between(adjusted, zdtNow);
// Display each part of the period and duration
System.out.printf("%d years %d month %d days %d hours %d minutes %d seconds %d nanoseconds", period.getYears(),
period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart(), duration.toNanosPart());
}
}
Output:
5 years 4 month 7 days 19 hours 30 minutes 37 seconds 507058000 nanoseconds
Using OffsetDateTime:
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.Period;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
// Define format
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH);
// Given date-time
OffsetDateTime givenDateTime = LocalDateTime.of(LocalDate.parse("12.03.2015", formatter), LocalTime.of(0, 0))
.atOffset(ZoneOffset.UTC);
// Now
OffsetDateTime odtNow = OffsetDateTime.now(ZoneOffset.UTC);
// Period between the two dates
Period period = Period.between(givenDateTime.toLocalDate(), odtNow.toLocalDate());
// Given date-time with current year, month and day
OffsetDateTime adjusted = givenDateTime.with(LocalDate.now(ZoneOffset.UTC));
// Duration between the two times
Duration duration = Duration.between(adjusted, odtNow);
// Display each part of the period and duration
System.out.printf("%d years %d month %d days %d hours %d minutes %d seconds %d nanoseconds", period.getYears(),
period.getMonths(), period.getDays(), duration.toHoursPart(), duration.toMinutesPart(),
duration.toSecondsPart(), duration.toNanosPart());
}
}
Following is the corrected version of your initial program. However as others pointed out it is advisable to use new java Time API.
There is nice article highlighting problem with old Java Date and Calendar API
https://programminghints.com/2017/05/still-using-java-util-date-dont/
import java.util.Date
import java.util.Locale
import java.time.Instant
import java.time.LocalDateTime
import java.time.LocalDate
import java.time.ZoneOffset
import java.text.SimpleDateFormat
import java.time.format.DateTimeFormatter
fun main(args: Array<String>) {
val sdf = SimpleDateFormat("dd.MM.yyyy")
val currentDate = Date()
val currentFormattedDate = sdf.format(currentDate)
println(currentFormattedDate)
val now = currentDate.getTime();
val stringDate = "12.03.2015"
val dateFormatter = DateTimeFormatter.ofPattern("dd.MM.yyyy", Locale.ENGLISH)
val millisecondsSinceEpoch = LocalDate.parse(stringDate, dateFormatter)
.atStartOfDay(ZoneOffset.UTC)
.toInstant()
.toEpochMilli()
println(millisecondsSinceEpoch)
val time = now - millisecondsSinceEpoch
val Datee = sdf.format(time)
println(Datee)
}
Thanks everyone. But I decided to do this. And it seems like everything works)
fun daysString(dataend: String):String{
val dateFormat = SimpleDateFormat("dd.MM.yyyy")
val endDate = dateFormat.parse(dataend)
val currentDate = Date()
val time = endDate.time - currentDate.time
val days = time / 1000 / 3600 / 24
val strtoday = days.toString()
return strtoday
}
Now in the code I am using:
val data_end = "10.10.2020"
daysString(data_end)
and I get strtoday
Get your required Date and then can do this:
val sdf = SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH)
val theDate = sdf.parse(selectedDate)
val selectedDate = theDate!!.time/86400000 //.time gives milliseconds
val currentDate = sdf.parse(sdf.format(System.currentTimeMillis()))
val currentDate = currentDate!!.time/86400000 //86400000 milliseconds in a day
val diff = currentDate - selectedDate
println(diffInMinutes.toString()) //set it to any view or use as needed

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

Match datetime property value in response value array list using groovy

I am trying to match if my datetime variable present in array of multiple dates but error popup displayed.
Error :
assert responseStartDateTime.contains(requestStartDateTime) | | | | false 2018-01-16T04:30:00 [2018-01-16T04:30:00, 2018-01-16T06:00:00]
Groovy code :
import groovy.json.JsonSlurper
import java.text.SimpleDateFormat
//request local time
def StartDateTime = context.expand('${#Project#StartDateTime}')
log.info 'Request StartTime : ' + StartDateTime
def EndDateTime = context.expand('${#Project#EndDateTime}')
log.info 'Request EndTime : ' + EndDateTime
//Remove Z from the request time
def outputDateFormat = "yyyy-MM-dd'T'HH:mm:ss"
start = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(StartDateTime)
end = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss").parse(EndDateTime)
def requestStartDateTime = "${start.format(outputDateFormat)}"
log.info 'Request StartTime : ' + requestStartDateTime
def requestEndDateTime = "${end.format(outputDateFormat)}"
log.info 'Request EndTime : ' + requestEndDateTime
def ResponseMessage = messageExchange.response.responseContent
def jsonSlurper = new JsonSlurper().parseText(ResponseMessage)
//Store response local time result to variable
def responseStartDateTime = jsonSlurper.MeetingItems.TimeFrom
log.info 'Response StartTime : ' + responseStartDateTime
def responseEndDateTime = jsonSlurper.MeetingItems.TimeTo
log.info 'Response EndTime : ' + responseEndDateTime
//Assert request local time with response local time
assert responseStartDateTime.contains(requestStartDateTime)
assert responseEndDateTime.contains(requestEndDateTime)
Property values :
StartDateTime - 2018-01-16T04:30:00.000Z
EndDateTime - 2018-01-16T04:45:00.000Z

Increment date to the next day using Groovy

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()

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"

Resources