Scala Last Year - scala

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)

Related

Trying to get the current date with a specific format but Date is coming with a expected way

Here is the code and output. Please let me know what's wrong with the code.
import java.text.SimpleDateFormat
def myDate=new Date()
def sdf= new SimpleDateFormat("MM/DD/YYYY")
return sdf.format(myDate)
log.info sdf.format(myDate)
Op-: 04/94/2016
Thanks!
You need lower case dd AND yyyy
You can also call format on dates directly in groovy
date.format('MM/dd/yyyy')
Also, if this is to be read by anyone outside the US, or you want to be able to sort dates alphabetically, consider the more universal (iso8601) format of
date.format('yyyy-MM-dd')
As AR.3 said in their answer, the documentation for simpledateformat can be found here

Scala Joda Time Format Malformed

I can't find many Scala examples with Joda time especially with formatting but here is the error:
Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2015-12-11T13:35:45.732-05:00" is malformed at "15-12-11T13:35:45.732-05:00"
Here is the code:
val now = DateTime.now.toString()
val dtf = DateTimeFormat.forPattern("MM-dd-yyyy HH:mm:ss");
val timeForm = dtf.parseDateTime(now)
Most of the java exmaples all seem to work fine with this?
It has nothing to do with Scala. MM-dd-yyyy HH:mm:ss means the string will start with month, then day, etc. (see http://joda-time.sourceforge.net/apidocs/org/joda/time/format/DateTimeFormat.html for the meaning of characters in the patterns). 2015-12-11T13:35:45.732-05:00 obviously doesn't. Either use val now = dtf.printDateTime(DateTime.now) to print current datetime in the same format you are planning to parse, or use the correct format to parse it.

Joda-time parser with instance-local default timezone

Is there an "instance-local" version of Joda's DateTimeZone.setDefault? I'm trying to achieve something like this:
val parser = new ParserWithDefaultTimezone("GMT+1");
parser.parse("1970-01-01 00:00:00").getMillis // -3600000L
parser.parse("1970-01-01 00:00:00 UTC").getMillis // 0L
Without polluting anything global. All I can find in the Joda docs is something that (ironically) modifies global state.
If there is a non-Joda solution, I am interested in that, too.
EDIT: Forgot to mention that if there is no ready-to-use class that does this, I'll settle for: "what is the easiest way to see if a time string contains an explicit timezone?" I can't distinguish between an explicit one and a timezone that Joda set by default.
EDIT 2: I don't have a format string to feed; I'm looking for something that infers the format at runtime.
You can use withZone to alter the date/time zone used:
val fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss ZZZ").withZone(DateTimeZone.forID("Europe/Berlin"))
val date = fmt.parseDateTime(???);
The set-up required to make the time zone optional is a little bit more complicated:
val tz = new DateTimeFormatterBuilder().appendLiteral(" ").appendTimeZoneId().toFormatter()
val fmt = new DateTimeFormatterBuilder()
.append(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"))
.appendOptional(tz.getParser())
.toFormatter().withZone(DateTimeZone.forID("Europe/Berlin"))
println(fmt.parseDateTime("1970-01-01 12:00:00 UTC"))
println(fmt.parseDateTime("1970-01-01 12:00:00 Europe/Berlin"))
println(fmt.parseDateTime("1970-01-01 12:00:00"))
As long as your remark
I don't have a format string to feed; I'm looking for something that infers the format at runtime.
applies only with respect to the time zone, solution 2 might do what you want. If, on the other hand, you really don't know, in wich format the dates are provided (dd/mm/yyyy vs. mm/dd/yyyy vs. yyyy/mm/dd vs. whatever), then I think you are out of luck: such a conversion would be ambiguous at best. Is 01/03/2015 the 1st of March or the 3rd of January?

How to find the previous two Sundays from the current day in 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}

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");