How to find the previous two Sundays from the current day in Scala? - scala

If current time is `2015-05-16 13:05:06+1793` then I should get `2015-05-03 00:00:00+0000` and `2015-05-10 00:00:00+0000`
If current time is `2015-05-10 00:00:00+0000` then I should get `2015-05-03 00:00:00+0000` and `2015-05-10 00:00:00+0000`
And so forth... How can I compute these two dates in scala?
EDIT:
As I mentioned, I would prefer a solution which is not at all based on external libraries. In addition, please mention explicitly all necessary imports I have to made cause I am a newby both in Java and Scala.

If you're on Java 8, you can do pretty well without joda-time.
import java.time.LocalDate
val today = new LocalDate()
val lastSunday = today minusDays ( today.getDayOfWeek.getValue % 7 ) // Monday = 1 ... Sunday = 7
val twoSundaysAgo = lastSunday minusDays 7

You can have a look at joda-time. It is the best library to manage dates.
In your case, you could create a LocalTime and use something like this:
d.plusWeeks(-2).withDayOfWeek(DateTimeConstants.SUNDAY))

For starters you probably want to be using joda-time, as Carlos suggested. One way to look at the problem would be to filter the right days out of a set of possible days. This would look something like the following:
val today: LocalDate = new LocalDate()
val sundays: Seq[LocalDate] = (1 to 13) map {date.minusDays(_)} filter {_.dayOfWeek() == DateTimeConstants.SUNDAY}

Related

Scala Last Year

I haven't been able to find an answer for this yet for Scala. I am trying to build a variable in scala for last year and last 2 months, and return in YYYY-MM-dd format. Here is what I have built out. Right now instead of the variable returning the expected date formatted the way im requesting the variable just returns the expression. Any thoughts on how I can change my code to present the variable last_year with the last year in a string format?
val last_year=date_sub(current_date()),365)
val last_2=date_sub(current_date()),60)
desired result: last_year= "2021-03-08"
last_2= "2021-01-08"
Here's the same result using the newer java.time library in place of the old and outdated Calendar and SimpleDate options.
val prev_yr = java.time.LocalDate.now().minusYears(1L).toString
Think I have the answer, just in case anyone needs this later on:
val cal:Calendar=Canlendar.getInstance()
val format=new SimpleDateFormat("YYYY-MM-dd")
cal.add(Calendar.Date,-365)
val prev_yr:String=format.format(cal.getTime)
println(prev_yr)

Add two date variables in Scala

I have a date string and a date interval which I want to add it to that date in Scala, but I don't know how I can do this (preferably without using Java Calendar)!
Something like this:
val d1 = new SimpleDateFormat("YYYY-MM-DD").parse("1999-12-01")
val d2 = ??? // 1 Year interval
d1 + d2
java.time
LocalDate d1 = LocalDate.parse("1999-12-01");
Period p2 = Period.ofYears(1);
LocalDate oneYearLater = d1.plus(p2);
System.out.println(oneYearLater);
Output from this snippet is:
2000-12-01
Sorry that I cannot write Scala code. I trust you to translate from Java.
Provided that you are based on at least Java 8 you don’t need an external library. For Java 6 and 7 use the same code, only add the ThreeTen Backport library to your project and import from the org.threeten.bp package. For Java 5 Joda-Time is the good solution, see the other answer.
Both java.time and the ThreeTen Backport were developed by the same folks that developed Joda-Time and drew heavily on the good (and the few poor) experiences from there. Joda-Time is now in maintenance mode. The Joda-Time home page says: “Note that Joda-Time is considered to be a largely “finished” project. No major enhancements are planned. If using Java SE 8, please migrate to java.time (JSR-310).”
Links
Oracle tutorial: Date Time explaining how to use java.time.
Java Specification Request (JSR) 310, where java.time was first described.
ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
ThreeTenABP, Android edition of ThreeTen Backport
Joda-Time hmoepage
You are better off using joda dates rather than "vanilla" java:
import org.joda.time.DateTime
val d1 = DateTime.parse("1999-12-01")
val d2 = d1.plusYears(1)
There is no need for external dependencies. You can use java.time.LocalDate:
import java.time.LocalDate
val date1 = LocalDate.parse("1999-12-01")
val date2 = date1.plusYears(1)
As mentioned, you can use the API provided by Java. However, and in case you need a more Scala-like library, you could use https://github.com/nscala-time/nscala-time which is a wrapper around JodaTime.
Some examples:
DateTime.now() + 2.months // returns org.joda.time.DateTime = 2009-06-27T13:25:59.195-07:00
DateTime.nextMonth < DateTime.now() + 2.months // returns Boolean = true
DateTime.now() to DateTime.tomorrow // return org.joda.time.Interval = > 2009-04-27T13:47:14.840/2009-04-28T13:47:14.840
(DateTime.now() to DateTime.nextSecond).millis // returns Long = 1000
2.hours + 45.minutes + 10.seconds // returns com.github.nscala_time.time.DurationBuilder
// (can be used as a Duration or as a Period)
(2.hours + 45.minutes + 10.seconds).millis // returns Long = 9910000
2.months + 3.days // returns Period
Cheers.

Mule - Date format from m/dd/yy to yyyy-mm-dd

want to convert date to the above required format. Is it possible to write a groovy script to do so in datamapper? If yes can you please give an example. Or can i reference another expression or component?
I think the simplest way to do what you need is to edit the datamapper script and replace the line where you perform the date mapping for this one:
output.date = date2str(str2date(input.date,"d/mm/yy"), "yyyy-mm-dd");
but replacing the input and output fields accordingly.
Here is the link which explains how to do it in java. You may easily groovify it.
Here the script
import java.text.SimpleDateFormat
def OLD_FORMAT = "m/dd/yy"
def NEW_FORMAT = "yyyy-MM-dd"
// August 12, 2010
def oldDateString = "8/12/10"
def sdf = new SimpleDateFormat(OLD_FORMAT)
def d = sdf.parse(oldDateString)
sdf.applyPattern(NEW_FORMAT)
newDateString = sdf.format(d)
println "Date in modified format : $newDateString"
EDIT:
Changed as per source format based on comment
#[server.dateTime.format('yyyy-MM-dd')]
I'm not a fan of such nesting.
I prefer a variation on the above answers, where I only keep the inner function:
output.date = str2date(input.date,"m/dd/yy")
but then defined the output format in the datamapper's graphical editor, by setting the field to a date with format "yyyy-MM-dd".
Both of these approaches work, but I find this method easier to read and far easier to explain to others.
You can also use format method in the expression to set the date as below :
flowVars.Timestamp = server.dateTime.format("YYYYMMDDHHmm");

Joda-Time : Date calculation

I would like to calculate precisely the months between two dates to achieve this I do something like :
DateTimeZone ZONE = DateTimeZone.forID("Europe/London");
String DATE_FORMAT = "dd/MM/yyyy";
DateTimeFormatter FORMATTER = DateTimeFormat.forPattern(DATE_FORMAT).withZone(ZONE);
LocalDate dateTime = FORMATTER.parseLocalDate("28/05/2013");
LocalDate dateTime6MonthAfter = FORMATTER.parseLocalDate("28/02/2014");
Period todayUntilEndOfContract = new Period(dateTime,dateTime6MonthAfter);
todayUntilEndOfContract.getMonths() +"M/"+ todayUntilEndOfContract.getWeeks() +"W/"+ todayUntilEndOfContract.getDays() +"D/");
So this give me precisely 9 month between 28/05/2013 and 28/02/2014 BUT!!!
when I calculate the dates (29, 30, 31)/05/2013 with 28/02/2014 it always give me 9 month normally it should say 8M/3W/(6,5,4)D/ why is it always 9M/0W/0D please...?
Thanks a lot
Your issue is that you are expecting something a little different than what is provided. If I ask you the question "what is 30th January plus one month?" then there are a number of different answers which are valid under different assumptions. In Joda's case the answer is "28th February" (or 29th if a leap year).
Although you are asking for month-based information I would suggest that you obtain the number of days instead and use that as a basis, as it is probably closer to what you need:
int days = Days.daysBetween(dateTime, dateTime6MonthAfter).getDays();
You can always use this number to feed back in to your code and obtain different values to fit your requirements.

zend_date relative time

i want to make stackoverflow timestamps(X minutes ago, etc). How i can make it using zend_date? I found How to calculate time passed with PHP or Zend_Date? this realisation, but it uses other library. Are there any different ways?
How about Zend_Date::subDate()?
$d1 = new Zend_Date();
$d2 = new Zend_Date($old_date);
$diff = $d1->subDate($d2);
After you've got the difference, you can check out one of these helpers:
Relative time view helper
Zend_View_Helper_Relativetime
Even if you don't want the whole Zym framework, you could still add their TimeSince view helper to your own application.
You can subtract timestamps of two dates to find difference between them in seconds and then use division and modulo to represent it as minutes, days etc.