Convert Date Time based on Locale - freemarker

Hello I am new to FTL Code and I am trying to re format a date based on how a locale would display it.
The error I am getting: (Please look below for more info of the result we want)
The string doesn't match the expected date/time/date-time format. The string to parse was: "août 26, 2035". The expected format was: "MM dd, yyyy".
The nested reason given follows:
Unparseable date: "août 26, 2035"
<#assign locale = userPreferences.getLanguage()>
my locale ${locale}<br>
<#if locale = "en_AU">
original = ${couponData.expiration}<br>
<#assign expiryDate = couponData.expiration?date("dd MM, yyyy")?string("dd MM yyyy")>
format ${expiryDate} <br>
${sys.declare("dateMonthYear", expiryDate)}
<#elseif locale = "en_GB">
original = ${couponData.expiration}<br>
<#assign expiryDate = couponData.expiration?date("MM dd, yyyy")?string("dd MM yyyy")>
format ${expiryDate} <br>
${sys.declare("dateMonthYear", expiryDate)}
<#elseif locale = "fr_CA">
original = ${couponData.expiration}<br>
<#assign expiryDate = couponData.expiration?date("MMM dd, yyyy")?string("dd MM. yyyy")>
format ${expiryDate} <br>
${sys.declare("dateMonthYear", expiryDate)}
<#else>
${sys.declare("dateMonthYear", "${couponData.expiration}")}
</#if>
CA_FR Source:
Ends Jul 31, 2022
Actual:
Expire le juil. 31, 2022
Expected:
Expire le 31 juil. 2022
EN_GB Source:
Ends Jul 31, 2022.
Actual:
Ends Jul 31, 2022.
Expected:
Ends 31 Jul 2022.
enter code here
EN_AU Source:
Ends Jul 31, 2022.
Actual:
Ends 31 Jul, 2022.
Expected:
Ends 31 Jul 2022.

I was able to solve my issue:
it seems in the string MM-DD-YY will format into something like 01/01/2022
Where as was proving three MMM-DD-YYYY will give me Jan 01, 2022
I can manipulate the dateformat inside the string also
<#setting locale="fr">
<#assign expirationDate = expiration?number_to_date?string("yyyy MMM. dd")>

Related

How to get the same output of departed Date.parse() in groovy?

I have an application that runs the old version of the spring application. The application has the function to create date objects using Date.parse as follows
Date getCstTimeZoneDateNow() {
String dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
def zonedDateString = new Date().format(dateFormat, TimeZone.getTimeZone('CST'))
Date date = Date.parse(dateFormat, zonedDateString)
return date // Tue Oct 18 20:36:12 EDT 2022 (in Date)
}
However, the code above is deprecated. I need to produce the same result.
I read other posts and it seems like Calender or SimpleDateFormatter is preferred.
And I thought SimpleDateFormatter has more capabilities.
This post helped me understand more about what is going on in the following code
SimpleDateFormat parse loses timezone
Date getCstTimeZoneDateNow() {
Date now = new Date()
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
SimpleDateFormat sdf = new SimpleDateFormat()
sdf.setTimeZone(TimeZone.getTimeZone('CST'))
// cstDateTime prints times in cst
String cstDateTime = sdf.format(now) // 2022-10-18T20:36:12.088Z (in String)
// JVM current time
Date date = sdf.parse(cstDateTime) // Tue Oct 18 21:36:12 EDT 2022 (in Date)
return date
}
Here my goal is to return the date object that is in the format of Tue Oct 18 20:36:12 EDT 2022
The format is good. However, like the post says, when I do sdf.parse(), it prints in JVM time.
This means, the format is good but the time zone is off.
How can I get the exact same result as before?
It does not have to use SimpleDateFormatter. Could be anything.
Thank you so much for reading and for your time.
Perhaps the important thing is, that the Date is always neutral to the timezone. Given example shows what is to be expected to work from the Java specs:
def format = new SimpleDateFormat()
format.setTimeZone(TimeZone.getTimeZone("CST"))
println new Date()
def date = format.parse(format.format(new Date()))
printf "parsed to %s%n", date
printf "formatted to %s (%s)%n", format.format(date), format.getTimeZone().getDisplayName()
In the output, notice when using the Format and when the toString(), a different time is shown accordingly, which is perfectly fine, since first we format and then parse again in the same format, thus the same time-zone. Later, we use the Date.toString() to output the date, this time using the system default time-zone which is always used when Date.toString() is called. In the output, the time-zone shift is reflected:
Thu Oct 20 09:22:58 EDT 2022
parsed to Thu Oct 20 09:22:00 EDT 2022
formatted to 10/20/22 8:22 AM (Central Standard Time)

Why isn't my Unix time parsing consistently?

My client generates a timestamp using Date.now(), generating a unix time in milliseconds. But when I parse it later on the server, I get a very different date. I can reproduce this discrepancy with Jsfiddle. My code is:
const parseMoment = moment('1603551654605', 'x').format();
const parseDate = new Date(1603551654605).toDateString();
alert(`moment: ${parseMoment}, date: ${parseDate}`);
The output I get is: moment: 2020-11-16T00:00:00+01:00, date: Sat Oct 24 2020
The correct output is what moment gives me here, 11/16. But moment on my server actually gives me the incorrect October date. I need to reliably parse my unix timestamp back to the correct (later) date.
The unix timestamp converts to Saturday, 24 October 2020 15:00:54.605 (GMT)
momentJS does't require any second parameters while creating a date from milliseconds (DOCS).
Using the correct conversion, both moment() and new Date() show the same result:
const parseMoment = moment(1603551654605).format();
const parseDate = new Date(1603551654605).toDateString()
console.log(`moment\t: ${parseMoment}`);
console.log(`date\t: ${parseDate}`);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
moment : 2020-10-24T17:00:54+02:00
date : Sat Oct 24 2020

How to convert string to NSDate that has extraneous characters (swift)?

I have the string "Sat, 21 Nov 2015 19:20:48 EST\n\t\t\t" that I need convert to NSDate, but it gives me nil all the time.
I tried to clear the string by
dateString.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
result looks fine: Sat, 21 Nov 2015 19:20:48. Converting to NSDate = nil :(
Ok, I removed the noised characters manually and try to convert the string "Sat, 21 Nov 2015 19:20:48 EST" to NSDate. Nil again:
let dateString = "Sat, 21 Nov 2015 19:20:48 EST"
let formatter = NSDateFormatter()
formatter.locale = NSLocale(localeIdentifier: 'US_en')
formatter.dateFormat = 'yyyy-MM-dd'
print("date = \(date)")
//date = nil
What am I doing wrong?
Even if I use "formatter.timeZone = NSTimeZone(abbreviation: "EST")" still nil.
Answer to your first question:
You could use the following code to trim the unwanted whitespace and newlines from the string
var dateAsString = "Sat, 21 Nov 2015 19:20:48 EST\n\t\t"
dateAsString = dateAsString.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
Answer to your second question:
Refer to the Date format symbols table in this link for list of all string formatting symbols.
You should be able to convert the specified date with this formatter,
let customDateFormatter = NSDateFormatter()
dayTimePeriodFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
let date = dayTimePeriodFormatter.dateFromString(dateAsString) //"Sat, 21 Nov 2015 19:20:48 EST"

(Swift) Using NSDataFormatter with a medium style string to get date

I seem to be stuck here and I have been wasting way too much tome on this.
What I have is a string that is in the RFC 1123 format that I would like to get a date out of, but not matter what I do, I get a nil result;
let dateFormat = NSDateFormatter();
dateFormat.dateStyle = .MediumStyle;
dateFormat.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss z";
dateFormat.locale = NSLocale.systemLocale();
dateFormat.timeZone = NSTimeZone(abbreviation:"GMT");
var currentDate = dateFormat.dateFromString("Sun, 28 Jun 2015 04:30:54 GMT");
I am not sure what I am missing, if I changed the MMM to MM and make Jun 06, then it works. It seems to be only this instance. I have tried moving the order of how dateFormat gets created, and still I get no results. Any help on this matter would greatly be appreciated
I think you have confused the formatter. You don't need to set anything except the format string, because the formatter's job is to learn those other settings from the string it reads.
let dateFormat = NSDateFormatter()
dateFormat.dateFormat = "EEE',' dd MMM yyyy HH':'mm':'ss z"
var currentDate = dateFormat.dateFromString("Sun, 28 Jun 2015 04:30:54 GMT")
// "Jun 27, 2015, 11:30 PM"
If you do as above, it will return an NSDate? from the date string you provided.

Ruby string.match() function fails with identical string within the to be matched string

I copied and pasted a smaller portion of a large string and matched it against the large string. However, it does not return the value back. In the NOT case, it returns true. Is there something to the match function I am missing, or could there be hidden characters?
times = File.readlines('timesplit')
stringcomp = "created_at : Tue Jul 02 03:30:50 +0000 2013 id : 351905778745094144 id_str : 351905778745094144"
times.each do |t|
r = t.split('|')
timestamp = r[1]
puts !stringcomp.match(timestamp)
puts stringcomp.match(timestamp)
end
Below are the contents for timesplit.
Jul_01|created_at : Tue Jul 02 03:30:50 +0000 2013 id :
Jul_02|created_at : Tue Sep 03 05:08:44 +0000 2013 id :
The problem is subtle. String.match expects a regular expression for its parameter, and, if it doesn't see one it tries to turn the parameter into an expression:
Converts pattern to a Regexp (if it isn’t already one), then invokes its match method on str.
So:
created_at : Tue Jul 02 03:30:50 +0000 2013 id :
isn't a pattern going in, and it gets converted to one.
The problem is the +. In regular expressions, + means one-or-more of the preceding character or group or character set.
The correct way to specify a literal match between your stringcomp and your newly created pattern would be for the pattern to be:
created_at : Tue Jul 02 03:30:50 \+0000 2013 id :
Notice the \+. That means the + is now a literal value, not a length specifier.
For visual proof, check these two Rubular tests:
Without escaping: http://rubular.com/r/L6Fwrw1ftf
Escaped: http://rubular.com/r/SjGAYtzHuS
That all said, the simple fix is to not try to use match, and instead use a substring search:
times = [
'Jul_01|created_at : Tue Jul 02 03:30:50 +0000 2013 id :',
'Jul_02|created_at : Tue Sep 03 05:08:44 +0000 2013 id :'
]
stringcomp = "created_at : Tue Jul 02 03:30:50 +0000 2013 id : 351905778745094144 id_str : 351905778745094144"
times.each do |t|
timestamp = t.split('|').last
puts stringcomp[timestamp] || 'sub-string not found'
end
Which outputs:
created_at : Tue Jul 02 03:30:50 +0000 2013 id :
sub-string not found
If you want a boolean result, instead of the matching substring being returned you can use:
!!stringcomp[timestamp]
For example:
!!stringcomp['created_at : Tue Jul 02 03:30:50 +0000 2013 id :'] # => true
Alternately, you could use Regexp.escape on your string, prior to passing it in to match, but I think that's overkill when a substring match will accomplish what you want.
You could also...
stringcomp.include? timestamp

Resources