I have always converted a Date into a Calendar using the setTime() method
Date date = new Date()
def calendar.setTime(date)
Recently I found the .toCalendar() method.
Date date = new Date()
def calendar = date.toCalendar()
What's the difference between them and which should I use?
As you can here this method does exactly the same:
public static Calendar toCalendar(Date self) {
Calendar cal = Calendar.getInstance();
cal.setTime(self);
return cal;
}
Related
Why everytime I make a
var date = DateTime.parse(dob);
var formattedDate = '${date.year}${date.month}${date.day}';
DateTime.parse(formattedDate)
it will still retrieve as 1961-02-26 00:00:00.000? How do I get it to become 19610226 but still in datatype DateTime?
Use DateFormat Class from intl package to format your date
var date = DateTime.parse(dob);
var dateFormatter = new DateFormat('yyyy-MM-dd');
String formattedDate = dateFormatter.format(date);
print(formattedDate); // result 2020-03-24
for more details and more formatting options see this answer
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've got a string (eg. "2014-11-06 16:32:01")
I want to turn this format into an NSDate object.
Here's what I'm doing:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
var date = dateFormatter.dateFromString("2014-11-06 16:32:01")!
var myCalendar:NSCalendar = NSCalendar(calendarIdentifier: NSGregorianCalendar)!
var myComponents = myCalendar.components(NSCalendarUnit.WeekdayOrdinalCalendarUnit, fromDate: date)
var year = myComponents.year
var month = myComponents.month
var day = myComponents.day
year, month, and day are each valued at 9223372036854775807. Am I getting the dateFormat wrong?
The date format is correct. But you have to specify all wanted units in the
myCalendar.components(...) call. All other components are set to NSNotFound aka NSIntegerMax,
which is 2^63 - 1 = 9223372036854775807 on the 64-bit architecture.
This should work:
var myComponents = myCalendar.components(.YearCalendarUnit | .MonthCalendarUnit | .DayCalendarUnit, fromDate: date)
static func convertStringToNSDate(dateStr: String) -> NSDate
{
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd HH':'mm':'ss '+0000'"
let date = dateFormatter.dateFromString(dateStr)
return date!
}
On my code I am using that method in order to convert a string to NSDate. The only thing that you need to do is to change the dateFormat attribute to be the same as the date's format you want to convert.
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);