Question 1: I have 2 fields to let user enter start date and end date, but in string format
- DateStart (string: yyyy/mm/dd hh:mm)
- DateEnd (string: yyyy/mm/dd hh:mm)
May I how to compare both datetime? I want to know total how many hours is difference between the both date.
Question 2: user will enter 1 returnDate (string: yyyy/mm/dd hh:mm) also in string format, may I know how to update the returnDate if I will need to add 55hours on the returnDate?
Thanks
Start by taking a look at SimpleDateFormat, which will allow you to convert the String value to a Date object.
For example...
try {
// Note hh is Hour in am/pm (1-12), based on you example, it's not possible
// now the day part (ie am or pm), you could supply aa as the am/pm marker
// or use HH which is Hour in day (0-23)
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd hh:mm");
Date date = sdf.parse("2014/04/11 4:46");
System.out.println(date);
} catch (ParseException exp) {
exp.printStackTrace();
}
Then you can use JodaTime to calculate the difference between the two dates, see How to find difference between two Joda-Time DateTimes in minutes for an example
It should be noted that you could skip the use of SimpleDateFormat and JodaTime all the way, check out String to joda LocalDate in format of "dd-MMM-yy" for an example of converting a String to a LocalDate using JodaTime
To add time to an existing Date, you can use either Calendar or JodaTime, see how to add days to java simple date format for an example of both
I would recommend that if you are using some kind of GUI, you might consider using one of the available date pickers as it will save you a lot of hassel
I suggest using Java8's java.util.time package
Example:
public static void main(String[] args) {
// example input
String dateString1 = "2014/04/10 00:00";
String dateString2 = "2014/04/11 23:59";
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
LocalDateTime date1 = LocalDateTime.parse(dateString1, dtf);
LocalDateTime date2 = LocalDateTime.parse(dateString2, dtf);
// do your stuff with the dates...
}
Here is my solution:
String date1 = "2014/04/10 15:30";
String date2 = "2014/04/11 09:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
try {
Date parsedDate1 = sdf.parse(date1);
Date parsedDate2 = sdf.parse(date2);
double secs = (parsedDate2.getTime() - parsedDate1.getTime()) / 1000;
double hours = secs / 3600;
System.out.println(hours);
} catch (ParseException e) {
e.printStackTrace();
}
For adding hours to a date:
Date date = new Date(someDateObject.getTime() + 55 * 3600 * 1000);
Related
How i can extract the Time alone in this format "2022-07-26T12:10:07.000+0000" and show in 12hrs.
The output i am supposed to get is "5:40 PM", but i am getting 12.10 AM.
How to get exact time in the above mentioned format?
This is the method i followed to parse the DateTime.
String getTimeStringNew(String date) {
DateFormat dateFormat = DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+SSSS");
var dateValue = dateFormat.parse(date);
DateFormat dateFormat1 = DateFormat("hh:mm a");
var value = dateFormat1.format(dateValue);
return value;}
In this method i am getting "12:10 AM".
But correct time is "5.40 PM".
What is the mistake i am doing here. Please correct.
2022-07-26T12:10:07.000+0000
Here 2022 is year
07 is month
26 is day
12 is hour
10 is minutes
07 is seconds.
So you will get 12.10 only
Maybe you are recieving the time in UTC.
You can use .toLocal to convert it to local time
var dateLocal = dateUtc.toLocal();
Edit
String getTimeStringNew(String date) {
DateTime _localDate = DateTime.parse(date).toLocal();
DateFormat dateFormat = DateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS+SSSS");
var dateValue = dateFormat.format(_localDate);
DateFormat dateFormat1 = DateFormat("hh:mm a");
var value = dateFormat1.format(_localDate);
return value;}
How can I change the Date format in dart
I get the from and to date difference value is int. How to change this integer to date format... and convert it to 0Days 0Months 7days;
I need this type of format
but I got this type of format
see the Vehicle Age:
vehicleAge(DateTime doPurchase, DateTime doRenewel) {
age = doPurchase.difference(doRenewel).abs().inDays.toInt();
return age;
}
That is my function...
Use this package time_machine and try this code
vehicleAge(DateTime doPurchase, DateTime doRenewel) {
LocalDate a = LocalDate.dateTime(doPurchase);
LocalDate b = LocalDate.dateTime(doRenewel);
Period diff = b.periodSince(a);
return "${diff.years} Years ${diff.months} Months ${diff.days} Days";
}
Try with this
vehicleAge(DateTime doPurchase, DateTime doRenewel) {
Duration parse = doPurchase.difference(doRenewel).abs();
return "${parse.inDays~/360} Years ${((parse.inDays%360)~/30)} Month ${(parse.inDays%360)%30} Days";
}
Correct Answer
I got a correct answer use jiffy package.
import 'package:jiffy/jiffy.dart';
then use this code
vehicleAge(DateTime doPurchase, DateTime doRenewel) {
var dt1 = Jiffy(doPurchase);
var dt2 = Jiffy(doRenewel);
int years = int.parse("${dt2.diff(dt1, Units.YEAR)}");
dt1.add(years: years);
int month = int.parse("${dt2.diff(dt1, Units.MONTH)}");
dt1.add(months: month);
var days = dt2.diff(dt1, Units.DAY);
return "$years Years $month Month $days Days";
}
I need to display tomorrow's date only , l have this code and his working fine without problem . and he is give the current date for today. l want change this code to get the date for tomorrow but l dont know how !
private fun date24hours(s: String): String? {
try {
val sdf = SimpleDateFormat("EE, MMM d, yyy")
val netDate = Date(s.toLong() * 1000)
return sdf.format(netDate)
} catch (e: Exception) {
return e.toString()
It is possible to use Date for this, but Java 8 LocalDate is a lot easier to work with:
// Set up our formatter with a custom pattern
val formatter = DateTimeFormatter.ofPattern("EE, MMM d, yyy")
// Parse our string with our custom formatter
var parsedDate = LocalDate.parse(s, formatter)
// Simply plus 1 day to make it tomorrows date
parsedDate = parsedDate.plusDays(1)
I might be late to the party, but this is what I found works for me
const val DATE_PATTERN = "MM/dd/yyyy"
internal fun getDateTomorrow(): String {
val tomorrow = LocalDate.now().plusDays(1)
return tomorrow.toString(DATE_PATTERN)
}
With LocalDate and DateTimeFormatter:
val tomorrow = LocalDate.now().plus(1, ChronoUnit.DAYS)
val formattedTomorrow = tomorrow.format(DateTimeFormatter.ofPattern("EE, MMM d, yyy"))
java.time
private fun date24hours(s: String): String? {
val zone = ZoneId.of("Asia/Dubai")
val dateFormatter = DateTimeFormatter.ofPattern("EE, MMM d, uuuu", Locale.forLanguageTag("ar-OM"))
val tomorrow = LocalDate.now(zone).plusDays(1)
return tomorrow.format(dateFormatter)
}
I never tried writing Kotlin code before, so there’s probably one or more bugs, please bear with me.
In any case the date and time classes that you were using — Date and SimpleDateFormat— had serious design problems and are now long outdated. I recommend you use java.time, the modern Java date and time API, instead.
Link: Oracle tutorial: Date Time explaining how to use java.time.
I'm new to Swift and not so familiar with date and time classes. I want to make an object of type Date that refers to sometime in the future (like several hours).
I'm not sure if this is going to be a UNIX timestamp or not.
How can I do that?
Swift Date (or NSDate) is a class in the Foundation framework. According to the docs:
The Date structure provides methods for comparing dates, calculating
the time interval between two dates, and creating a new date from a
time interval relative to another date. Use date values in conjunction
with DateFormatter instances to create localized representations of
dates and times and with Calendar instances to perform calendar
arithmetic.
So you'd want to make use of the Calendar class to do date conversions. Something like this should do the job:
func getDateTimeForHoursInTheFuture(hours: Int) -> Date {
var components = DateComponents();
components.setValue(hours, for: .hour);
let date: Date = Date();
let expirationDate = Calendar.current.date(byAdding: components, to: date);
return expirationDate!;
}
Of course it can be changed to work with minutes and seconds instead of hours.
You can format the output using:
extension Date {
func toDateTimeString() -> String {
let formatter = DateFormatter();
formatter.dateFormat = "yyyy-MM-dd HH:mm:ss";
let myString = formatter.string(from: self);
return myString;
}
}
Just call the toDateTimeString() method on the result of getDateTimeForHoursInTheFuture function.
I am attempting to parse a date string of (almost) arbitrary length. The approach I had with SimpleDateFormat was something like this
private Date parseWithSimpleDateFormat(String dateString) throws ParseException {
String pattern = "yyyyMMddHHmmss".substring(0, dateString.length());
SimpleDateFormat format = new SimpleDateFormat(pattern);
return format.parse(dateString);
}
... which I want to do "better" with the new Date API. What I've come up with is the following
private static final DateTimeFormatter FLEXIBLE_FORMATTER = new DateTimeFormatterBuilder()
.appendPattern("yyyy[MM[dd[HH[mm[ss]]]]]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
private Date parseWithDateTimeFormatter(String dateString) {
LocalDateTime localDateTime = LocalDateTime.parse(dateString, FLEXIBLE_FORMATTER);
ZonedDateTime zonedDateTime = localDateTime.atZone(ZoneId.systemDefault());
Instant instant = zonedDateTime.toInstant();
return Date.from(instant);
}
with the following outcome
parseWithDateTimeFormatter("2016"); // works as intended
parseWithDateTimeFormatter("201605"); // Text '201605' could not be parsed at index 0
parseWithDateTimeFormatter("20160504"); // Text '20160504' could not be parsed at index 0
parseWithDateTimeFormatter("2016050416"); // Text '2016050416' could not be parsed at index 0
parseWithDateTimeFormatter("201605041636"); // Text '201605041636' could not be parsed at index 0
What am I doing wrong here, or how would I further troubleshoot this?
You can use this modified formatter in order to avoid parsing more than 4 digits for the year:
private static final DateTimeFormatter FLEXIBLE_FORMATTER =
new DateTimeFormatterBuilder()
.appendValue(ChronoField.YEAR, 4)
.appendPattern("[MM[dd[HH[mm[ss]]]]]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, 1)
.parseDefaulting(ChronoField.DAY_OF_MONTH, 1)
.parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
.parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
.parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
.toFormatter();
In contrast to other fields like month (MM) etc., the year field symbol y has no limitation to four digits as indicated by count of y-letters.