How to trim Full Year and Seconds in DateTime - movilizer

I am getting Date as '2/12/2020 4:30:29 PM'. But i need trimmed year and seconds date time format like
'12/02/20 04:30 PM'
what is the equivalent function in MEL for getting above date time?
Thanks

I'm afraid there isn't an equivalent function in MEL to do this thing. BUT the good news is that you can create it! (yes, MEL needs more time functions to work...).
I've create this global function that you can use it (I assume 2 is day and 12 is month, if not you can change the order):
separator = "/";
space = " ";
hourSeparator = ":";
$global:stringDatetimeToArray = function(datetime)
{
array['year'] = substring(datetime, 6, 10);
array['month'] = substring(datetime, 3, 5);
array['day'] = substring(datetime, 0, 2);
array['hour'] = substring(datetime, 11, 13);
array['minute'] = substring(datetime, 14, 16);
array['seconds'] = substring(datetime, 17, 19);
array['meridian'] = substring(datetime, 20, 22);
return array;
};
concat(array['month'], separator, array['day'], separator, array['year'], space, array['hour'], hourSeparator, array[minute], space, array['meridian']);
My recommendation for you is to generate a method that converts a timestamp into an array of these values, and then you can work with these kind of issues easier than now. You can see an example on this github script

import re
date_str = '2/12/2020 4:30:29 PM'
sub_str = re.search(':\d+(.*?)\s',date_str).group(1)
date_str = date_str.replace(sub_str,'')
print(date_str)
Output: 2/12/2020 4:30 PM

Related

Calendar.set error or infinite loop

the following does not seem to work, it seems to cause an infinite loop:
import java.text.SimpleDateFormat;
SimpleDateFormat out=new SimpleDateFormat('yyyy-MM-dd');
def from = Calendar.instance
from.set(year: 2017, month: Calendar.JANUARY, date: 3)
def to = Calendar.instance
to.set(year: 2017, month: Calendar.FEBRUARY, date: 3)
from.upto(to) {
cal=it;
prev=cal;
prev.set(Calendar.DAY_OF_MONTH, 1);
println out.format(prev.getTime());
}
can somebody please explain why this should not work? I don't get it. My goal is to get the first day of month within the upto loop.
Inside the loop, you are constantly setting the calendar back to the first day of the month...
It's similar to if you did:
for (int i = 0; i < 10; i++) {
i = 0
println i
}
(that will never finish either)
Also, you code will run for every day between the two dates... which I don't think is what you are looking for either
It's easier if you use immutable things over Calendar, and as you're on Java 8, you can do:
import java.time.*
import java.time.format.*
// Add a next method, so you can do ranges of LocalDates
LocalDate.metaClass.next = { delegate.plusDays(1) }
LocalDate from = LocalDate.of(2017, 1, 3)
LocalDate to = LocalDate.of(2017, 2, 3)
(from..to).each {
println it.format(DateTimeFormatter.ISO_DATE) + " : " + it.withDayOfMonth(1).format(DateTimeFormatter.ISO_DATE)
}

Wrong hour difference between 2 timestamps (hh:mm:ss)

Using moment.js, I want to get the time difference between 2 timestamps.
Doing the following,
var prevTime = moment('23:01:53', "HH:mm:SS");
var nextTime = moment('23:01:56', "HH:mm:SS");
var duration = moment(nextTime.diff(prevTime)).format("HH:mm:SS");
I get this result :
01:00:03
Why do I have a 1 hour difference? seconds and minutes seem to work well.
After doing that, I tried the following :
function time_diff(t1, t2) {
var parts = t1.split(':');
var d1 = new Date(0, 0, 0, parts[0], parts[1], parts[2]);
parts = t2.split(':');
var d2 = new Date(new Date(0, 0, 0, parts[0], parts[1], parts[2]) - d1);
return (d2.getHours() + ':' + d2.getMinutes() + ':' + d2.getSeconds());
}
var diff = time_diff('23:01:53','23:01:56');
output is : 1:0:3
The problem you are having here is that when putting the nextTime.diff() in a moment constructor, you are effectively feeding milliseconds to moment() and it tries to interpret it as a timestamp, which is why you don't get the expected result.
There is no "nice way" of getting the result you want apart from getting a time and manually reconstructing what you are looking for :
var dur = moment.duration(nextTime.diff(prevTime));
var formattedDuration = dur.get("hours") +":"+ dur.get("minutes") +":"+ dur.get("seconds");
And a more elegant version that will give you zero padding in the output :
var difference = nextTime.diff(prevTime);
var dur = moment.duration(difference);
var zeroPaddedDuration = Math.floor(dur.asHours()) + moment.utc(difference).format(":mm:ss");
Should make you happier!
EDIT : I have noticed you use HH:mm:SS for your format, but you should instead use HH:mm:ss. 'SS' Will give you fractional values for the seconds between 0 and 999, which is not what you want here.

How to find the biggest number in a string that contains not just numbers but words?

How to find the biggest number in a string that contains not just numbers but words?
For example:
String naa = "John 19, Reuben 21, sbu 6, Derick 33";
I need to be able to find the highest age no mater the names and ages entered.
I'm not sure what language you are trying to use but one way to do this in ruby for example would be
str = "John 19, Reuben 21, sbu 6, Derick 33;"
str.gsub(/\d+/).map { |i| i.to_i }.max
What this does is the following:
str.gsub(/\d+/)
Returns all the numbers as an enumerator
The map command then changes them all to integers and returns an Array with the integers.
Then we just call max on that array.
Java
String[] ss = "John 19, Reuben 21, sbu 6, Derick 33;".split("[^\\d]");
System.out.println(Arrays.asList(ss));
int max = Integer.MIN_VALUE;
for(String s:ss){
try{
if (Math.max(Integer.valueOf(s), max) != max){
max = Integer.valueOf(s);
}
}catch(NumberFormatException nfe){}
}
System.out.println(max);
Try this in java
Pattern p = Pattern.compile("[0-9]?[0-9]");
Matcher m = p.matcher(naa) ;
List<Integer> listInt = new ArrayList<Integer>();
while (m.find()) {
int age = Integer.parseInt(m.group());
listInt.add(age);
}
int max = Collections.max(listInt);
System.out.println( max);

Date in X-Axis - .Net Charts

i am working in .Net Charts. i want to show date in X-Axis. For ex : if i select Last 52 Weeks, then i should show the chart for last 52 weeks, whereas those 52 weeks start date should be in x-axis. I am not having any idea, how to do this..I had tried with the code..
DateTime Frm = sessionManager.ChartViewPeriodFrom;
DateTime To = sessionManager.ChartViewPeriodTo;
double min = Frm.ToOADate();
double max = To.ToOADate();
Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = min;
Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = max;
Chart1.ChartAreas["ChartArea1"].AxisX.Interval = 7;
Here i am getting the Frm as "9/17/2011 12:00:00 AM" But, in the chart the minimum date starts from "9/21/2011 12:00:00 AM". How to fix this...
I had tried like this also..[ Edited Part ]
Chart1.Series["Series1"].XValueType = ChartValueType.Date;
Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = (new DateTime(2011, 09, 17, 12, 00, 00)).ToOADate();
Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = (new DateTime(2012, 09, 08, 12, 00, 00)).ToOADate();
Chart1.ChartAreas["ChartArea1"].AxisX.Interval = 7;
Chart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = false;
After a long search...i had fixed my above issue...but still i dont know how it works...
Chart1.ChartAreas["ChartArea1"].AxisX.IntervalAutoMode = IntervalAutoMode.VariableCount;
Chart1.Series["Series1"].XValueType = ChartValueType.Date;
DayOfWeek ds = DayOfWeek.Wednesday;
double dblIntervalOffset = Convert.ToDouble(ds);
Chart1.ChartAreas["ChartArea1"].AxisX.IntervalOffset = dblIntervalOffset;
Chart1.ChartAreas["ChartArea1"].AxisX.Minimum = min;
Chart1.ChartAreas["ChartArea1"].AxisX.Maximum = max;
Chart1.ChartAreas["ChartArea1"].AxisX.Interval = 7;
Chart1.ChartAreas["ChartArea1"].AxisX.IsMarginVisible = false;
Indexed attribute must be set for series data.

Convert NTP timestamp to utc

Whats the easiest way to convert an NTP timestamp to utc. I know it's in NTP, I can convert it into any other format.
Thanks.
Bob.
As rene pointed out the NTP timestamp is made up of an integer and a fractional part. The integer part represents the number of seconds since base time, which is 1st Jan 1900. The fractional part represents the number of fractional units (a unit is 1/((2^32)-1)) in the second.
Also, the time representation is UTC.
Therefore, if you have an NTP Timestamp of say 14236589681638796952. NTP is a 64-bit unsigned fixed-point number. We can say:
UInt64 ntpTimestamp = 14236589681638796952;
The high 32 bits are given by:
UInt32 seconds = (UInt32)((ntpTimestamp >> 32) & 0xFFFFFFFF);
And the low 32 bits are are given by:
UInt32 fraction = (UInt32)(ntpTimestamp & 0xFFFFFFFF);
The number in seconds is equal to the most significant word or in this case:
seconds == 3314714339
The number of milliseconds can be calculated from the fraction using this calculation:
Int32 milliseconds = (Int32)(((Double)fraction / UInt32.MaxValue) * 1000);
Which is 12 in this case.
Thus the DateTime value is yielded from:
DateTime BaseDate = new DateTime(1900, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
DateTime dt = BaseDate.AddSeconds(seconds ).AddMilliseconds(milliseconds);
Therefore the NTP Timestamp of 14236589681638796952 is equal to the 14th Jan 2005 at 17:58:59 and 12 milliseconds UTC.
This works reliably, for me:
#define NTP_TIMESTAMP_DIFF (2208988800) // 1900 to 1970 in seconds
#define NTP_MAX_INT_AS_DOUBLE (4294967295.0) // Max value of frac
// take care of the endianness
reply_pkt.tx_time_sec = ntohl( reply_pkt.tx_time_sec ) ;
reply_pkt.tx_time_frac = ntohl( reply_pkt.tx_time_frac ) ;
// parse
time_t tx_time = ( time_t ) ( reply_pkt.tx_time_sec - NTP_TIMESTAMP_DIFF );
double frac = ((double)reply_pkt.tx_time_frac) / NTP_MAX_INT_AS_DOUBLE ; // 2^32 -1
struct tm *tm = gmtime(&tx_time) ;
char ts[49];
strftime(ts,48,"[%Y-%m-%d %H:%M:%S]",tm);
printf("NTP query: reply was %s\n",ts);
ntp_time_seconds = ((double)tx_time) + frac ;
Try something like this? I'm not sure on the format of that 'seconds since Jan 1 1900', but you can modify as you see fit.
long ntp = 3490905600;
DateTime start = new DateTime(1900, 1, 1);
DateTime dt = start.AddSeconds(ntp);
Console.WriteLine(dt.ToString());
Console.WriteLine(dt.ToUniversalTime().ToString());

Resources