When I use the Simple Data Writer and save responses to a file where the time is:
Date: Thu, 09 Aug 2018 15:13:51 GMT
I want to post the current timing which is 11 something i.e., this time - 4.
How to change this?
If this Date: Thu, 09 Aug 2018 15:13:51 GMT is a part of your response and you need to change it on the fly you can do this using JSR223 PostProcessor and Groovy language.
The relevant code which will extract the date from the response, subtract 4 hours from it and replace the old date with the new date would be something like:
def response = prev.getResponseDataAsString()
log.info("Full response: " + response)
use(groovy.time.TimeCategory) {
def detectedDate = (response =~ "Date: (.+) GMT")[0][1]
Date oldDate = Date.parse("EE, dd MMM yyyy HH:mm:ss", detectedDate)
Date newDate = oldDate - 4.hour
log.info("Old date: " + oldDate)
log.info("New date: " + newDate)
response = response.replace(detectedDate, newDate.format("EE, dd MMM yyyy HH:mm:ss"))
prev.setResponseData(response, "UTF-8")
}
Demo:
More information:
Groovy Goodness: Working with Dates
Apache Groovy - Why and How You Should Use It
Related
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)
I have timestamp for one of my http sampler in following format
Tue Nov 07 10:28:10 PST 2017
and i need to convert it to in following format
11/07/2017 10:28:10
i tried different approaches but don't know what am i doing wrong.Can anyone help me on that.Thanks.
It's very similar to how you'd do it in Java.
Here's an example:
import java.text.DateFormat;
import java.text.SimpleDateFormat;
String string = "Tue Nov 07 10:28:10 PST 2017";
// Original format to convert from
DateFormat formatFrom = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ENGLISH);
// Target format to convert to
DateFormat formatTo = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss", Locale.ENGLISH);
// Parse original string, using original format
Date date = formatFrom.parse(string);
// Convert to a target format
String result = formatTo.format(date);
// Just to show the output, not really necessary
log.info(result);
One catch: since target format omits the zone, local zone of the computer will be used. So for example original time 10:28:10 PST will be converted to 10:28:10 for computer in PST zone, but for computer in EST zone it will be converted to 13:28:10
I heard Groovy is the new black so given:
Date class in Groovy SDK has format() and parse() methods
It is recommended to use JSR223 Test Elements and Groovy language since JMeter 3.1
you can get the date converted in a single line of Groovy code like:
Date.parse("EEE MMM dd HH:mm:ss zzz yyyy", 'Tue Nov 07 10:28:10 PST 2017').format("dd/MM/yyyy HH:mm:ss", TimeZone.getTimeZone('PST'))
Demo:
I get this format from javascript :
"Fri Mar 17 2017 20:27:32 GMT 0100 (CET)"
But when i parse it i get this:
0100-03-19 20:19:48
So i get year 100.
Im using this function:
$date = Carbon::parse($date);
Any suggestion?
I think you need to add a plus before the 0100 part, but other than that, you can use createFromFromat method:
$date = Carbon::createFromFormat("D M d Y H:i:s e O T", "Fri Mar 17 2017 20:27:32 GMT +0100 (CET)"));
I have two strings , which are each got from respective shell commands and are not uniformly formatted.
Two strings obtained are as follows:
Date : Tue Feb 28 16:23:20 2017 -0600
Executed at : Tue Feb 28 17:24:06 EST 2017
EDIT: I get the above mentioned dates , one through git log and other through cat and store both in variables
First date is got through and stored in X:
sh 'git log <file> | grep Date | head -n 1 > X '
Second date is got through below and stored in Y:
sh 'cat chef-policy-release.log | grep <file> | tail -n 1 | grep -o "Executed at.*" > Y'
Now I wanted to pick out just date and time among that and wanted to check if executed time is after the Date value or not ?
Similar to Rao's answer, but with a function to parse the string, no need for date format strings, and without creating un-needed Date instances:
class DateTest{
public static void main(String[] args) {
String logDateString = args[0];
String execDateString = args[1];
Date logDate = parseDate(logDateString);
Date execDate = parseDate(execDateString);
System.out.println(execDate > logDate);
}
static def parseDate(String rawString) {
String dateString = rawString.substring(rawString.indexOf(":") + 1).trim();
new Date(Date.parse(dateString));
}
}
Here you go.
def dateStr1 = 'Tue Feb 28 16:23:20 2017 -0600'
def dateStr2 = 'Tue Feb 28 17:24:06 EST 2017'
def pattern1 = "EEE MMM dd HH:mm:ss yyyy Z"
def pattern2 = "EEE MMM dd HH:mm:ss z yyyy"
def date = new Date().parse(pattern1, dateStr1)
def executeDate = new Date().parse(pattern2, dateStr2)
assert date < executeDate, 'Execute Date is earlier than the date'
You may quickly try it online (negative test)Demo
EDIT: Based on OP's comment to parse the string and extract the date
You could have applied #GreBeardedGeek's parsing logic.
//Closure to get the date parsed
def getDate = { delimiter, dateFormat, dateStr ->
def dt = dateStr.substring(dateStr.indexOf(delimiter) + 1).trim()
println dt
new Date().parse(dateFormat, dt)
}
def dateStr1 = 'Date : Tue Feb 28 16:23:20 2017 -0600'
def dateStr2 = 'Executed at : Tue Feb 28 17:24:06 EST 2017'
def pattern1 = "EEE MMM dd HH:mm:ss yyyy Z"
def pattern2 = "EEE MMM dd HH:mm:ss z yyyy"
def date = getDate(':', pattern1, dateStr1)
def executeDate = getDate(':', pattern2, dateStr2)
assert date < executeDate, 'Execute Date is earlier than the date'
Edit#2 can be more simplified to:
//Set / assign the two dates
def dateStr1 = 'Date : Tue Feb 28 16:23:20 2017 -0600'
def dateStr2 = 'Executed at : Tue Feb 28 17:24:06 EST 2017'
def getDate = { dateStr -> Date.parse(dateStr.substring(dateStr.indexOf(':') + 1).trim()) }
assert getDate(dateStr1) < getDate(dateStr2), 'Execute Date is earlier than the date'
Simple question, but I can't find a good or definitive answer. What is the best and most efficient way to combine Ruby Date and Time objects (objects, not strings) into a single DateTime object?
I found this, but it's not as elegant you would hope:
d = Date.new(2012, 8, 29)
t = Time.now
dt = DateTime.new(d.year, d.month, d.day, t.hour, t.min, t.sec, t.zone)
By the way, the ruby Time object also stores a year, month, and day, so you would be throwing that away when you create the DateTime.
When using seconds_since_midnight, changes in daylight savings time can lead to unexpected results.
Time.zone = 'America/Chicago'
t = Time.zone.parse('07:00').seconds_since_midnight.seconds
d1 = Time.zone.parse('2016-11-06').to_date # Fall back
d2 = Time.zone.parse('2016-11-07').to_date # Normal day
d3 = Time.zone.parse('2017-03-12').to_date # Spring forward
d1 + t
#=> Sun, 06 Nov 2016 06:00:00 CST -06:00
d2 + t
#=> Mon, 07 Nov 2016 07:00:00 CST -06:00
d3 + t
#=> Sun, 12 Mar 2017 08:00:00 CDT -05:00
Here's an alternative, similar to #selva-raj's answer above, using string interpolation, strftime, and parse. %F is equal to %Y-%m-%d and %T is equal to %H:%M:%S.
Time.zone = 'America/Chicago'
t = Time.zone.parse('07:00')
d1 = Time.zone.parse('2016-11-06').to_date # Fall back
d2 = Time.zone.parse('2016-11-07').to_date # Normal day
d3 = Time.zone.parse('2017-03-12').to_date # Spring forward
Time.zone.parse("#{d1.strftime('%F')} #{t.strftime('%T')}")
#=> Sun, 06 Nov 2016 07:00:00 CST -06:00
Time.zone.parse("#{d2.strftime('%F')} #{t.strftime('%T')}")
#=> Sun, 07 Nov 2016 07:00:00 CST -06:00
Time.zone.parse("#{d3.strftime('%F')} #{t.strftime('%T')}")
#=> Sun, 12 Mar 2017 07:00:00 CDT -05:00
Simple:
Date.new(2015, 2, 10).to_datetime + Time.parse("16:30").seconds_since_midnight.seconds
# => Object: Tue, 10 Feb 2015 16:30:00 +0000
You gotta love Ruby!
If using Rails, try any of these:
d = Date.new(2014, 3, 1)
t = Time.parse("16:30")
dt = d + t.seconds_since_midnight.seconds
# => ActiveSupport::TimeWithZone
dt = (d + t.seconds_since_midnight.seconds).to_datetime
# => DateTime
dt = DateTime.new(d.year, d.month, d.day, t.hour, t.min, t.sec)
# => DateTime
If you are using Ruby on Rails, this works great.
I built a method to extend the DateTime class to combine a date and a time. It takes the zone from the date so that it does not end up an hour off with daylight savings time.
Also, for convenience, I like being able to pass in strings as well.
class DateTime
def self.combine(d, t)
# pass in a date and time or strings
d = Date.parse(d) if d.is_a? String
t = Time.zone.parse(t) if t.is_a? String
# + 12 hours to make sure we are in the right zone
# (eg. PST and PDT switch at 2am)
zone = (Time.zone.parse(d.strftime("%Y-%m-%d")) + 12.hours ).zone
new(d.year, d.month, d.day, t.hour, t.min, t.sec, zone)
end
end
So you can do:
DateTime.combine(3.weeks.ago, "9am")
or
DateTime.combine("2015-3-26", Time.current)
etc...
I found another way, I hope this is correct.
datetojoin=Time.parse(datetime).strftime("%Y-%m-%d")
timetojoin=Time.parse(time).strftime("%T")
joined_datetime = Time.parse(datetojoin +" "+ timetojoin).strftime("%F %T")
Any thoughts? Please share.