Java on dates
JDate: Date/time
Don't forget to check the documentation for the JDate Class
Creating a date from an Mx date
JDate jDate=_doJava.getNewJDate();
if (!jDate.set(_str1))
return "";
return jDate;
Retrieving the current datetime
JDate jDatenow=_doJava.getNewJDate();
jDatenow.setTimeInMillis(System.currentTimeMillis());
return jDatenow;
Computing a date in Excel format (corresponding to number of days after 1900) to date in Mx (days after 1970)
JDate jDate1=_doJava.getNewJDate();
if (!jDate1.set(_str1)){
jDate1.setTimeInMillis((Str.ToLong(_str1)-25568)*24*60*60*1000);
if (jDate1==null)
return "";
jDate1.setHour(0);
jDate1.setMinute(0);
jDate1.setSecond(0);
}
return jDate1;
Computing a datetime with hours in Excel format (Ex: 0,25 = 8h)
In this case _str1 is a date, _str2 a number or string. We remove what is before the comma (or period) in order to get 1,25 in the cell, which means 8h the next day (even though Excel would only display 08:00).
if (_str1.equals("") || _str2.equals(""))
return "";
JDate jDate=_doJava.getNewJDate();
if (!jDate.set(_str1))
return "";
int seconde=0;
// dealing with scientific notation. Ex: 4,1666667E-2 = 0,041666 = 1h00m
double hour = Str.ToDouble(_str2);
String str_hour = String.format("%.6f", hour);
if (str_hour.contains("."))
seconde=(int)(Str.ToDouble("0."+Str.RemoveBefore(str_hour,"."))*24*3600.01);
if (str_hour.contains(","))
seconde=(int)(Str.ToDouble("0."+Str.RemoveBefore(str_hour,","))*24*3600.01);
jDate.setSecond(seconde);
return jDate.formatYYYYMMDD_HHMMSS();
Computing a datetime with number of days in the year
Here we've got number of days in a year in _str1 (example : 317 = 20191113) and the year in the name of the file
(step2 is to get the year from the name of file : )
String step1 = Str.RemoveBefore(_str3,"_");
String step2 = Str.RemoveAfter(step1,"_");
JDate jdate = _doJava.getNewJDate(step2+"0101_000000");
jdate.setMonth(0);
jdate.setDay(Str.ToIntOrZero(_str1));
return jdate;
Using SPLIT and SWITCH to create a date in MXformat from a String
First, you should try to use the '''simpleDateFormat''' option in the Originals variable setup page in mx.
If your variable has been identified as a STRING, force it to a DATEHOUR. Then in the "Date format" dropdown, select '''SimpleDateFormat'''. Finally, in the "Optional formatting" text box, put your format string. The available codes are available here : [docs.oracle.com Java Doc for SimpleDateFormat]
On the example above, that would be '''HH:mm dd EEE yyyy'''
On the following : '''Sun Dec 16 2018 16:34:00 GMT+0100 (GMT+01:00)''' that is '''EEE MMM dd yyyy HH:mm:ss''' (you can forget about the timezone)
If your really love writing java, or if you have a really funky date format, here is an example to parse it:
Example converting '''06:48 13 Sep 2018''' to '''20190913_064800'''
if (Str.CountWords(_str1," ")<=2)
return "";
String[] parts = _str1.split(" ");
String time = parts[0];
String jour = parts[1];
String mois = parts [2];
String annee = parts [3];
String[] parts1 = time.split(":");
String heure = parts1[0];
String minute = parts1[1];
switch (mois) {
case "Jan" : mois = "01"; break;
case "Feb" : mois = "02"; break;
case "Mar" : mois = "03"; break;
case "Apr" : mois = "04"; break;
case "May" : mois = "05"; break;
case "Jun" : mois = "06"; break;
case "Jul" : mois = "07"; break;
case "Aug" : mois = "08"; break;
case "Sep" : mois = "09"; break;
case "Oct" : mois = "10"; break;
case "Nov" : mois = "11"; break;
case "Dec" : mois = "12"; break;
}
return annee + mois + jour + "_" + heure + minute + "00";
Recreating a date from small pieces and testing it
String date = "";
String var1 = Str.RemoveBefore(_str1,"_");
date = var1.substring(6,10) + var1.substring(3,5) + var1.substring(0,2) + "_" + var1.substring(11,13) + var1.substring(14,16) + "00";
JDate j1=_doJava.getNewJDate();
if (!j1.set(date))
return "";
return date;
Concatenating the date (_str1) and time (_str2) from two different columns
JDate jDate1=_doJava.getNewJDate();
JDate jDate2=_doJava.getNewJDate();
if (!jDate1.set(_str1))
return "";
if (!jDate2.set(_str2))
return "";
jDate1.setHour(jDate2.getHour());
jDate1.setMinute(jDate2.getMinute());
jDate1.setSecond(jDate2.getSecond());
return jDate1;
Adding the minutes and seconds of two dates
Ex A break duration of 3min15 is represented by 19700101_000315, we have the break start date and we want the break end date.
JDate jDate1=_doJava.getNewJDate();
if (!jDate1.set(_str1))
return "";
JDate jDate2=new JDate();
if (!jDate2.set(_str2))
return "";
jDate1.setMinute(jDate1.getMinute() + jDate2.getMinute());
jDate1.setSecond(jDate1.getSecond() + jDate2.getSecond());
return jDate1;
// ================================
// New MX Common function
// ================================
/**
* Description : Removing everything after first non-numeric character
* Input : Date _str1
* Date _str2
* Output : Date _str1 + minutes/seconds of _str2
*/
return MxDate_add_minutes_seconds_2_dates(_doJava, _str1, _str2);
Creating a date from a format (v1.16)
JDateConversion jDateConversion = new JDateConversion(_str6, _doJava.getTimeZone());
JDate jDate6=jDateConversion.getDate("MM/dd/yyyy");
// If the conversion worked and the year is after 2000 and not in the future:
if (jDate6 != null && jDate6.getYear()>2000 && jDate6.getTimeInMillis() < System.currentTimeMillis())
return jDate6;
// Attempting another format
jDate6=jDateConversion.getDate("yyyy/MM/dd");
// If the conversion worked, the year is after 2000 and not in the future:
if (jDate6 != null && jDate6.getYear()>2000 && jDate6.getTimeInMillis() < System.currentTimeMillis())
return jDate6;
Creating a date from an automatic format (v1.16)
JDateConversion jDateConversion = new JDateConversion(_str1, _doJava.getTimeZone());
String strFormatDate = jDateConversion.getFormatDate();
if (strFormatDate.length()!=0)
{
JDate jDate=jDateConversion.getDate(strFormatDate);
if (jDate!=null)
return jDate;
}
return "";
Parsing a date in the ISO 8601 Format, with or without Timezone This code parses dates like
- '''2019-06-19T19:19:19''' no TZ no ms
- '''2019-06-19T19:19:19.325''' no TZ with ms
- '''2019-06-19T19:19:19M''' with TZ no ms
- '''2019-06-19T19:19:19.325M''' with TZ and ms
The letters at the end defines an UTC timezone as per [wikipedia : List of UTC time offsets on Wikipedia].
Cases where UTC timezone contains a special character are not managed (like for French Polynesia TZ).
It returns a TD jDate. Note that you'll loose the millisecondes. If you want to deal with milliseconds, check [[Simple_operations_with_dates#Converting a string to a timestamp to get the milliseconds|Converting a string to a timestamp to get the milliseconds]]. Basically you have to set up your variable datatype as a STR or a NBR and return the milliseconds.
try {
JDate jDate = _doJava.getNewJDate();
long date = parseDate("2019-06-19T19:19:19.325M").getTime();
jDate.setTimeInMillis(date);
return jDate;
} catch (java.text.ParseException pe) {
return pe;
}
}
static Date parseDate(String dateString) throws java.text.ParseException, IndexOutOfBoundsException {
Date d;
if (Character.isLetter(dateString.charAt(dateString.length() - 1))) {
String TZ = Str.Right(dateString, 1);
String UTCTZ = "";
switch (TZ) {
case "A":
UTCTZ = "+01:00";
break;
case "B":
UTCTZ = "+02:00";
break;
case "C":
UTCTZ = "+03:00";
break;
case "D":
UTCTZ = "+04:00";
break;
case "E":
UTCTZ = "+05:00";
break;
case "F":
UTCTZ = "+06:00";
break;
case "G":
UTCTZ = "+07:00";
break;
case "H":
UTCTZ = "+08:00";
break;
case "I":
UTCTZ = "+09:00";
break;
case "K":
UTCTZ = "+10:00";
break;
case "L":
UTCTZ = "+11:00";
break;
case "M":
UTCTZ = "+12:00";
break;
case "N":
UTCTZ = "-01:00";
break;
case "O":
UTCTZ = "-02:00";
break;
case "P":
UTCTZ = "-03:00";
break;
case "Q":
UTCTZ = "-04:00";
break;
case "R":
UTCTZ = "-05:00";
break;
case "S":
UTCTZ = "-06:00";
break;
case "T":
UTCTZ = "-07:00";
break;
case "U":
UTCTZ = "-08:00";
break;
case "V":
UTCTZ = "-09:00";
break;
case "W":
UTCTZ = "-10:00";
break;
case "X":
UTCTZ = "-11:00";
break;
case "Y":
UTCTZ = "-12:00";
break;
case "Z":
UTCTZ = "+00:00";
break;
}
dateString = Str.Left(dateString, dateString.length() - 1) + UTCTZ;
//step one, split off the timezone.
String firstPart;
String secondPart;
if (dateString.lastIndexOf('+') == -1) {
firstPart = dateString.substring(0, dateString.lastIndexOf('-'));
secondPart = dateString.substring(dateString.lastIndexOf('-'));
} else {
firstPart = dateString.substring(0, dateString.lastIndexOf('+'));
secondPart = dateString.substring(dateString.lastIndexOf('+'));
}
//step two, remove the colon from the timezone offset
secondPart = secondPart.substring(0, secondPart.indexOf(':')) + secondPart.substring(secondPart.indexOf(':') + 1);
dateString = firstPart + secondPart;
java.text.SimpleDateFormat s = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
try {
d = s.parse(dateString);
} catch (java.text.ParseException pe) { //try again with optional decimals
s = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ", Locale.getDefault());
s.setLenient(true);
d = s.parse(dateString);
}
} else {
try {
java.text.SimpleDateFormat s = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.getDefault());
d = s.parse(dateString);
} catch (java.text.ParseException pe) { //try again with optional decimals
java.text.SimpleDateFormat s = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS", Locale.getDefault());
s.setLenient(true);
d = s.parse(dateString);
}
return d;
}
return d;
Creating a date column from a date contained in a filename
_str1 = lien_mxfile (Available columns => Systems => Filename in), and in this example the filename is: ''FileName_yyyyMMdd#HHmmss.par''
// Do it in an Entrance Java Computing (as a system column is needed)
// Cutting up the file name
String step1 = Str.RemoveBefore(_str1,"_");
String step2 = Str.RemoveAfter(step1,".par");
// Retrieving the date and time separately
String heure = Str.RemoveBefore(step2,"#");
String date = Str.RemoveAfter(step2,"#");
String date_heure = "";
date_heure = date + "_" + heure;
JDate j1=_doJava.getNewJDate();
if (!j1.set(date_heure))
return "";
return j1;
Converting an UNIX date to an Mx date
// If _str1 = the number of seconds since jan. 1st, 1970 (you must have 10 characters).
Long heure = (long) (Str.ToDouble(_str1)*JDatePeriod.ONE_SECOND);
JDate jDate=_doJava.getNewJDate();
jDate.setTimeInMillis(heure);
jDate.setSecond(0);
return jDate;
If you have 13 characters it means you have milliseconds
Long heure = (long) (Str.ToDouble(_str1)*JDatePeriod.ONE_SECOND)/1000;
JDate jDate=_doJava.getNewJDate();
jDate.setTimeInMillis(heure);
jDate.setSecond(0);
return jDate;
Converting a string with simple date format
try
{
java.text.SimpleDateFormat simpleDateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
simpleDateFormat.setTimeZone(_doJava.getTimeZone());
java.util.Date date = simpleDateFormat.parse(_str1);
JDate jDate = _doJava.getNewJDate();
jDate.setTime(date);
return jDate;
}
catch (java.text.ParseException ex)
{
return null;
}
For dates in another locale (like US in the example below), don't forget to add Locale.US in the format string. for am/pm, use only one "a" and "hh" instead of "HH" :
try
{
java.text.SimpleDateFormat DateToConvert = new java.text.SimpleDateFormat("MMM dd yyyy hh:mma", Locale.US);
DateToConvert.setTimeZone(_doJava.getTimeZone());
java.util.Date date = DateToConvert.parse(_str1);
JDate jDate = _doJava.getNewJDate();
jDate.setTime(date);
return jDate;
}
catch (java.text.ParseException MyCaughtError)
{
return null;
}
Result:
Oct 28 2016 1:42PM ==> 20161028_134200
Converting a GMT date in local date
JDate jDate=_doJava.getNewJDate();
jDate.setTimeZone(JDate.TimeZoneGMT);
if (!jDate.set(_str1))
return "";
jDate.setTimeZone(_doJava.getTimeZone());
return jDate;
Voici un site de conversion rapide qui peut vous aider : epochconverter
Converting TD_Timestamp into millisec timestamp
JDate jDate=_doJava.getNewJDate();
if (!jDate.set(_str1))
return _str1;
return jDate.getTimeInMillis() ;