How to convert english date to Chinese and Korean - date

I have tried to implement locale for date. But it is working fine except for Chinese and Korean Language. For Chinese and Korean language, '??' is coming in the place of month.
Language: Groovy,grails 1.3.7
please see the code below
Date from=new Date(params.from)
Date to=new Date(params.to)+1
//params.from and params.to is in english
dateMap.from=from
dateMap.to=to
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy",locale)
String fromDate
String toDate
fromDate=sdf.format(from)
toDate=sdf.format(to)
println "fromdate :"+fromDate
output is
fromdate :09-??-2015
This is working fine for all other languages.
Please see below one more code i tried.
locale=new Locale("zh","CN")
SimpleDateFormat dateFormatCN = new SimpleDateFormat("dd-MMM-yyyy", locale);
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
Date temp = dateFormat.parse("05-Sep-2013");
println "temp :"+temp
String out=dateFormatCN.format(temp);
println "out :"+out
output :
temp :Thu Sep 05 00:00:00 IST 2013
out :05-??-2013

This is a problem with your console.
I tried the below in groovyConsole and it worked
import java.text.SimpleDateFormat
def params = [to: '05-Sep-2013', from: '05-Sep-2013']
def locale=new Locale("zh","CN")
Date from=new Date(params.from)
Date to=new Date(params.to)+1 //params.from and params.to is in english
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy",locale)
String fromDate
String toDate
fromDate=sdf.format(from)
toDate=sdf.format(to)
println "fromdate :"+fromDate​

Related

Unparseable date error format in Spring Boot Mongo DB

MongoCollection<Document> Profile_List = db.getCollection("Profile_List");
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());
ArrayList<Document> activeList=profile.find(Filters.regex("lastActive",todayDate.toString())).into(new ArrayList<Document>());
This is the code what we have written. We are getting an “Unparseable date error”. Can someone please help?
This is wrong:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD");
Date todaydate = format.parse(new Date().toString());
The expression new Date().toString() does not return a string that conforms to the format yyyy-MM-DD, so if you try to parse it as if it is formatted that way, you will get an exception.
If you want a Date object that represents the current date and time, simply do this:
Date todaydate = new Date();
No need to convert the Date object to a string and trying to parse it.
If you need a string with the current date in the format yyyy-MM-dd then do this:
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
String todaydate = format.format(new Date());
Note: You used DD in your date format string but you most likely meant dd. See the API documentation of SimpleDateFormat.
If you are trying to get the current date string in yyyy-MM-dd format. You can do format it like this
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String dateString = simpleDateFormat.format(new Date());

Adding time to SimpleDateFormat in Groovy

I am trying to add time to groovy parameter which have DateTime stored in SimpleDateFormat.
import groovy.time.TimeCategory
import java.text.SimpleDateFormat
def testCase = messageExchange.modelItem.testCase;
def startdatetime = testCase.testSuite.project.getPropertyValue("StartDateTime").toString();
log.info startdatetime
aaa = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'").parse(startdatetime)
use(TimeCategory)
{
def enddatetime = aaa + 5.minutes
log.info enddatetime
}
startdatetime : Wed Nov 08 19:57:50 IST 2017:INFO:2017-11-08T15:00:00.000Z
Error popup displayed with message
'Unparseable date: "2017-11-08T15:00:00.000Z"'
If the date string is Wed Nov 08 19:57:50 IST 2017 and you want to convert it to date object, then you could do:
def dateString = "Wed Nov 08 19:57:50 IST 2017"
def dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
def date = Date.parse(dateFormat, dateString)
Looks you wanted to add 5 minutes to it which can be done as did already
def endDate
use(TimeCategory) { endDate = date + 5.minutes }
log.info "End date : $endDate"
If you want the date object to formatted, then do:
def outputDateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
log.info "Formatted date: ${date.format(outputDateFormat)}"
Another suggestion after looking at your code to get the project property value, use below one-liner.
Change From:
def testCase = messageExchange.modelItem.testCase;
def startdatetime = testCase.testSuite.project.getPropertyValue("StartDateTime").toString();
To:
def startDateTime = context.expand('${#Project#StartDateTime}')
Instead of "yyyy-MM-dd'T'HH:mm:ss'Z'" you probably want "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" since your input string includes milliseconds.
I have got no experience with Groovy, but I assume that since you can use Java classes, you can also use the modern Java date and time API. I much recommend that over the long outdated SimpleDateFormat class. Your format, 2017-11-08T15:00:00.000Z, is in no way tied to SimpleDateFormat, on the contrary, it’s ISO 8601, the format that the modern date and time classes (as opposed to the old ones) “understand” natively without the need for an explicit formatter for parsing.
So I suggest you try (by no means tested):
import java.time.Instant
import java.time.temporal,ChronoUnit
and
aaa = Instant.parse(startdatetime)
and maybe (if you still need or want to use the Java classes)
enddatetime = aaa.plus(5, ChronoUnit.MINUTES)

I have a string date format 01/01/2017 6:54 PM and want to convert it to 2017-01-01T00:00:05.383+0100 ISOFormat in scala

def cleantz( time : String ) : String = {
var sign_builder= new StringBuilder ++= time
println(sign_builder)
var clean_sign = ""
if (sign_builder.charAt(23).toString == "-"){
clean_sign= sign_builder.replace(23,24,"-").toString()
}else{
clean_sign = sign_builder.replace(23,24,"+").toString()
}
var time_builder= new StringBuilder ++= clean_sign
if (time_builder.charAt(26).toString == ":"){
val cleanz = time_builder.deleteCharAt(26)
cleanz.toString()
}else{
time_builder.toString()
}
}
val start = ISO8601Format.parse(cleantz(01/01/2017 6:54 PM))
I get this error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 23
java.time
For the sake of completeness I should like to contribute the modern answer. It’s quite simple and straightforward.
I am sorry that I can neither write Scala code nor test it on my computer. I have to trust you to translate from Java.
private static DateTimeFormatter inputFormatter
= DateTimeFormatter.ofPattern("MM/dd/yyyy h:mm a", Locale.US);
public static String cleantz(String time) {
return LocalDateTime.parse(time, inputFormatter)
.atOffset(ZoneOffset.ofHours(1))
.toString();
}
Now cleantz("01/01/2017 6:54 PM") returns 2017-01-01T18:54+01:00, which is in ISO 8601 format. I would immediately suppose that you’re set. If for some reason you want or need the seconds too, replace .toString(); with:
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
Now the result is 2017-01-01T18:54:00+01:00. In both cases the milliseconds would have been printed if there were any.
Since AM and PM are hardly used in other languages than English, I suggest you give an English-speaking locale to DateTimeFormatter.ofPattern() (in my example I used Locale.US). Failing to provide a locale will cause the code to fail on many computers with non-English language settings.
Why java.time?
SimpleDateFormat and friends are long outdated and notoriously troublesome. I cannot count the questions asked on Stack Overflow because SimpleDateFormat behaved differently from what every sane programmer would have expected, or offered no help to debug the simple errors we all make from time to time.
Joda-Time was good for a long time. Today the Joda-Time homepage 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).
java.time is the modern Java date & time API built using the experience from Joda-Time and under the same lead developer, Stephen Colebourne. It is built into Java 8 and later, and a backport exists for Java 6 and 7, so you can use the same classes there too.
Assuming that your input string is 01/01/2017 6:54 PM: it has 18 characters. When you call charAt(23), it tries to get the character at position 23, which doesn't exist: the string has positions from zero (the first 0) to 17 (the M). If you try to get a position greater than that, it throws a StringIndexOutOfBoundsException.
But you don't need to do all this string manipulation. If you have a string that represents a date in some format, and want to convert it to another format, all you need is:
parse the original string to a date
format this date to another format
So you need 2 different Joda formatter's (one for each step). But there's one additional detail.
The input has a date (01/01/2017) and a time (6:54 PM), and the output has a date (2017-01-01), a time (18:54:00.000) and the UTC offset (+0100). So you'll have an additional step:
parse the original string to a date
add the +0100 offset to the parsed date
format this date to another format
With Joda-Time, this can be achieved with the following code:
import org.joda.time.DateTimeZone
import org.joda.time.LocalDateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.ISODateTimeFormat
val fmt = DateTimeFormat.forPattern("dd/MM/yyyy h:mm a")
// parse the date
val localDate = LocalDateTime.parse("01/01/2017 6:54 PM", fmt)
// add the +01:00 offset
val dt = localDate.toDateTime(DateTimeZone.forOffsetHours(1))
// format to ISO8601
print(ISODateTimeFormat.dateTime().print(dt))
The output will be:
2017-01-01T18:54:00.000+01:00
Note that the offset is printed as +01:00. If you want exactly +0100 (without the :), you'll need to create another formatter:
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
println(formatter.print(dt))
The output will be:
2017-01-01T18:54:00.000+0100
This is the code I used to achieve the same result. The error occurred because I was trying to parse the wrong date format.
val inputForm = new SimpleDateFormat("MM/dd/yyyy h:mm a")
val outputForm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
val dateFormat1 = start_iso
val dateFormat2 = stop_iso
val start = outputForm.format(inputForm.parse(start_iso))
val stop = outputForm.format(inputForm.parse(stop_iso))
println(start)
println(stop)

Convert a jmeter variable of milliseconds to a formatted date

I cant seem to convert a date in milliseconds (1488520800000) extracted from JSON and put into a variable into a formatted date (2017-03-02). Here's my code:
import java.text.*;
import java.util.*;
SimpleDateFormat source = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
SimpleDateFormat target = new SimpleDateFormat("yyyy-MM-dd");
Date date = source.parse(vars.get("varReviewDatevalue"));
String newDate = target.format(date);
vars.put("varFormattedReviewdateValue",newDate);
Here's the error I get:
ERROR - jmeter.util.BeanShellInterpreter: Error invoking bsh method: eval Sourced file: inline evaluation of: ``import java.text.*; import java.util.*; log.info("value for variable: 14885208 . . . '' : Typed variable declaration : Method Invocation source.parse
What's weird is that I got similar code to work fine for an extracted date like: March 2, 2017. I can't figure out why the date represented in mills is not converting to a date. Any ideas?
I was using the wrong jmeter element. This post helped me alot: JMeter: Converting extracted time stamp value to date format
I put this code into a JSR223 Sampler and everything worked
import java.text.*;
long timeStamp = Long.parseLong(vars.get("varReviewDatevalue"));
Date date = new Date(timeStamp);
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
TimeZone tzInAmerica = TimeZone.getTimeZone("America/Denver");
formatter.setTimeZone(tzInAmerica);
String dateFormatted = formatter.format(date);
vars.put("varFormattedReviewdateValue", dateFormatted);
log.info(dateFormatted);
log.info(vars.get("varFormattedReviewdateValue"));

DateTime format not formatting correctly

I have a datetime format in XML and I'm trying to unmarshall the values as follows:
2013-03-17T19:12:14Z -> 2013-03-17 19:12 +0100
I have used Joda's DateTime and a DateTimeAdapter class to override the unmarshalling. The datetime format is coming out weird, as follows:
{"iMillis":1363510800000,"iChronology":{"iBase":{"iBase":{"iBase":
{"iMinDaysInFirstWeek":4}},"iParam":{"iZone":{"iTransitions":
[-9223372036854775808,-3852662325000,-1691964000000,-1680472800000,
-1664143200000,-1650146 400000,-1633903200000,-1617487200000,
-1601848800000,- etc etc.
Can anyone help me format this date?
I was unable to figure out the answer so I've tried the following:
SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm Z");
DateTime dateTime = new DateTime(v);
long dateTimeMiliSec = dateTime.getMillis();
Date date = new Date(dateTimeMiliSec);
return sd.format(date);
So 2013-03-17T09:00:00Z converts to 2013-03-17 09:00 +0000