I have to find the last date of the last month
I am using a Groovy Script
I can get the date part ok but now I have to turn it into a String in the form yyyyMMdd.
Code so far (and yes it works)
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.Date;
Calendar aCalendar = Calendar.getInstance();
// add -1 month to current month
aCalendar.add(Calendar.MONTH, -1);
// set actual maximum date of previous month
aCalendar.set(Calendar.DATE,aCalendar.getActualMaximum(Calendar.DAY_OF_MONTH));
//read it
lastDateOfPreviousMonth = aCalendar.getTime();
This returns the date in timestamp form
20160229 105925.240
Now I need to extract 20160229 from the timestamp as a string
I've tried just about everything...
If this is running on Java 8, you can use the new Java Time classes:
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAdjusters
String date = LocalDate.now()
.minusMonths(1)
.with(TemporalAdjusters.lastDayOfMonth())
.format(DateTimeFormatter.ofPattern("yyyyMMdd"))
If this is Java 7 or Java 6, you can use Calendar and a bit of Groovy:
String date = Calendar.instance.with {
add(MONTH, -1)
set(DAY_OF_MONTH, getActualMaximum(DAY_OF_MONTH))
time
}.format('yyyyMMdd')
Related
how to show datetime(timestamp format) form firebase firestore in (dd/mm/yy, hh:mm:ss) in flutter.
please see the images attachedfirebase firestore data
and my code is my code in vscode
You can simply call toDate() function to the dateTime or your firebase timestamp.
You can also convert them into desired format by using DateFormat class
Here is a small function which will return time like 12:37 AM :
import 'package:intl/intl.dart'; //add this import statement for using DateTime class
String getTime(var time) {
final DateFormat formatter = DateFormat('dd/MM/yyyy, hh:mm:ss aa'); //your date format here
var date = time.toDate();
return formatter.format(date);
}
This function will convert your timestamp object to provided format
eg.: July 23, 2021 at 9:22:29 PM UTC+5:30 -> 23/07/2021, 9:22:29 PM
You can refer this document for detailed date formatting.
You can first parse the date to get a DateTime object by using DateTime.parse(string_from_firebase).
Then use the DateFormat class from the intl package.
final DateTime dateToBeFormatted = DateTime.parse(string);
final df = DateFormat('dd/MM/yyyy');
final formatted = df.format(dateToBeFormatted);
i have a really simple problem, i don't know how to deduct the user's date by 01/01 / (the user year) +1. Im really stuck at this point.
public static void main(String[] args)
{
String date;
Scanner teclado = new Scanner (System.in);
System.out.println("Dame una fecha formato dd/mm/yyyy");
date=teclado.next();
Date mydate =FinalAnio.ParseFecha(date);
System.out.println(mydate);
}
public static Date ParseFecha(String fecha)
{
SimpleDateFormat formato = new SimpleDateFormat("dd/mm/yyyy");
Date fechaDate = null;
try
{
fechaDate = formato.parse(fecha);
}
catch (ParseException ex)
{
System.out.println(ex);
}
return fechaDate;
}
The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API.
For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.
If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.
Do not use mm for the month as it is used for the minute. For the month, the correct symbol is MM. Check DateTimeFormatter to learn more about various symbols used for parsing/formatting string/date-time.
Learn about the calculations of the period and duration from Period and Duration tutorial from Oracle. It would also be worth going through this Wikipedia page on Durations.
Demo:
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Locale;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter date in the format dd/MM/yyyy: ");
String strDate = scanner.next();
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd/MM/uuuu", Locale.ENGLISH);
LocalDate userDate = LocalDate.parse(strDate, dtf);
// The date representing 01/01/(the user year)+1
LocalDate targetDate = userDate.withDayOfMonth(1).withMonth(1).plusYears(1);
System.out.println("User's date: " + strDate);
System.out.println("Target date: " + targetDate.format(dtf));
Period period = Period.between(userDate, targetDate);
System.out.printf("Difference: %d days %d months %d years%n", period.getDays(), period.getMonths(),
period.getYears());
System.out.println("The difference in terms of days: " + ChronoUnit.DAYS.between(userDate, targetDate));
}
}
A sample run:
Enter date in the format dd/MM/yyyy: 20/10/2015
User's date: 20/10/2015
Target date: 01/01/2016
Difference: 12 days 2 months 0 years
The difference in terms of days: 73
Learn about the modern date-time API from Trail: Date Time.
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work.
DateTimeFormatter formatador = DateTimeFormatter.ofPattern("dd/MM/uuuu");
String entradaUsuario = "02/12/2020";
LocalDate fecha = LocalDate.parse(entradaUsuario, formatador);
LocalDate finDeAño = fecha.with(MonthDay.of(Month.DECEMBER, 31));
long diasRestantes = ChronoUnit.DAYS.between(fecha, finDeAño);
System.out.println(diasRestantes);
Output is:
29
In the format pattern string upper case MM is for month of year (lower case mm would be minute of hour, so not useful here). uuuu is for year (yyyy would work too).
fecha.with(MonthDay.of(Month.DECEMBER, 31)) adjusts the date to December 31 in the same year.
Link
Oracle tutorial: Date Time explaining how to use java.time.
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)
I have a set of dates stored as UTC in my database, when I import them in Salesforce using the tSalesforceOutput:
If I run the import from my machine, they get the wrong timezone
If I run the import from a server which is in UTC, they get the correct timezone.
Is Talend/Salesforce API using the local timezone? How can I prevent this?
Salesforce will allways convert datetime from user timezone to UTC before to store them.
To avoid any problem, the simpler is to fix the user timezone used for the Salesforce connection to GMT and to explicitly convert each datetime to this timezone before to call any tSalesforceOutputXxxx component.
Here is a routine you can use for this purpose:
package routines;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;
public class dateConversion {
public static String convertToGmt(String strDate, String timezone) throws Exception
{
if (strDate == null || timezone == null)
return null;
// Convert strDate from any valid TimeZone such as Europe/Paris to GMT
// strDate is expected to be formatted as "yyyy-MM-ddTHH:mm:ssZ"
SimpleDateFormat indfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
indfm.setTimeZone(TimeZone.getTimeZone(timezone));
Date inDate = indfm.parse(strDate);
SimpleDateFormat outdfm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
outdfm.setTimeZone(TimeZone.getTimeZone("GMT"));
String s = outdfm.format(inDate);
return s;
}
}
Hope this helps.
TRF
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"));