I'm trying to get all the accounts that have EXPIRED using accountExpires attribute in Active Directory.
As the attribute type is Int8 (64-bit integer) and coldfusion does not support such long integer, I am having a hard time getting this to work.
Is there a function or some sort that I can use to acheive the above?
Thanks!
A 64 bit integer in Java is a java.lang.Long. Longs are implicitly converted to Integers in ColdFusion.
accountExpires is a windows file time structure representing the number of 100-nanosecond intervals since January 1, 1601. This thread shows how we can get a windows file time to date:
long diff1601to1970 = 315532800 * 1000000000; // <-- diff in nanoseconds(1/1/1601 to 1/1/1970)
long currentFrom1970 = System.currentTimeMillis() * 1000000;
long currentFrom1601 = diff1601to1970 + currentFrom1970;
Which allows us to do the following in ColdFusion:
accountExpiresFileTime = 129407978957060010;
date = createObject("java", "java.util.Date").init(
(accountExpiresFileTime-116444736000000000)/10000
);
Hopefully that helps.
Related
I want to store a Javascript Date() object in a spreadsheet with correct format according to spreadsheet's locale (SpreadsheetApp.getActive().getSpreadsheetLocale()).
Is there a way to get the country specific (date and) time format string from the spreadsheet locale?
E.g. when locale is de_DE, time format string as hh:mm
but when locale is da_DK, time format string as hh.mm
Interesting as well how to get the countries currency format.
BTW when I have date and time in de_DE and than change to da_DK, dates are reformatted (23.01.2020 -> 23/01/2020) but times are not (it stays as 22:59). Is that an error in Spreadsheet?
Dates in JavaScript have the method toLocaleDateString, which return a string formatted according to the specified locale. But this doesn't seem to work in Apps Script.
If you're open to using an Apps Script Web App for this, you could use this toLocaleDateString in your client-side script (that is, in a script tag in your HTML).
If that's not the case, I think your best option would be to create the relationship between formats and locales yourself, because Apps Script doesn't have a built-in method to achieve that. You could, for example, use a switch statement that would check the locale, and then format the date accordingly with Utilities.formatDate, the tool Apps Script uses to format dates. It could be something along the following lines:
var locale = SpreadsheetApp.getActive().getSpreadsheetLocale();
var formattedDate;
switch (locale) {
case 'de_DE':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh:mm");
break;
case 'da_DK':
formattedDate = Utilities.formatDate(yourDate, yourTimeZone, "hh.mm");
break;
// ...
}
return formattedDate;
Reference:
toLocateDateString
Apps Script Web Apps
Utilities.formatDate
I hope this is of any help.
Sorry for that, however I found a function that would be worth checking out, it's toLocaleDateString() and toLocaleTimeString (), they deliver the local date and time format.
Please check
Formato fechas JavaScript.
I did the test from Google Apps Script and it throws me the following
function pruebafecha() {
var d = new Date();
var n = d.toLocaleDateString();
var h = d.toLocaleTimeString();
Logger.log(n);
Logger.log(h);
}
This is the answer(Colombia):
[20-01-24 16:47:50:286 EST] 24 de enero de 2020
[20-01-24 16:47:50:287 EST] 16:47:50 EST
A JavaScript Date object includes date, time and timezone. When Google Apps Script pass a Date object to the spreadsheet using setValue() / setValues() the value is displayed according to the cell number formatting using the spreadsheet timezone.
If the cell formatting is set to Automatic by default the date will be displayed accordingly to the spreadsheet locale.
If you want to force the cell to display a date in an specific format use Class Range setNumberFormat / setNumberFormats
If you don't want to use the above methods and don't want to rely on the spreadsheet locale and automatic cell format then instead of passing a Date object pass the value as an string prepending it with an ' (apostrophe, single quote character) to prevent that that automatic data type parsing changes the value and it's format.
Related
Javascript in Google Sheets script: help using setNumberFormat
I don't know very well the configuration of the sheet you mention. However, I share a code that I use to print the date and time of data submission of a form.
var d = new Date();
var hour = d.getHours()-1;
var min = d.getMinutes();
var day = d.getDate();
var month = d.getMonth()+1;
var year = d.getFullYear();
if (month<10) {dia = day+"/"+"0"+month+"/"+year;}
else {dia = day+"/"+month+"/"+year;}
if (min<10){time = hour+":"+"0"+min;}
else {time = hour+":"+min;}
What I do in the code is to take the values of day, month and year, I add 1 to the value of month because it takes values [0:11] => [Jan, Dec].
Then I build the format I want from date and time, you can notice that I have 1 left to the hours, because when I did the tests I noticed that the time of the script was one hour above.
I use google translate, I hope it is understood.
I tried everything to get the current year/month/date/hour but it doesn't work. I always get data 1 hour behind. So if it's 17:00 in the Netherlands, I get 16:00. I have tried so many things, but I can't get this fixed.. is it a bug?
I Tried this:
string dateTimeNowPlusForecaseHour = DateTimeOffset.Now.ToLocalTime().AddHours(hour).ToString("yyyyMMddhh");
And this:
string dateTimeNowPlusForecaseHour = DateTimeOffset.UtcNow.ToLocalTime().AddHours(hour).ToString("yyyyMMddhh");
And this:
string dateTimeNowPlusForecaseHour = DateTimeOffset.UtcNow.ToLocalTime().AddHours(hour).ToString("yyyyMMddhh");
And this:
string dateTimeNowPlusForecaseHour = DateTimeOffset.Now.AddHours(hour).ToString("yyyyMMddhh");
And this:
public string GetForecastTime(int hour)
{
// Take amount of seconds elapsed since 1970
var amountOfSecondsElapsedSince1970 = new DateTimeOffset(DateTime.UtcNow).ToUnixTimeSeconds();
// Make a Datetime variable (1970 is the start)
System.DateTime dateTimeNowString = new DateTime(1970, 1, 1, 1, 0, 0, 0, System.DateTimeKind.Utc);
// Add amountOfSecondsElapsedSince1970 to the date time starting at 1970, + the amount of hours (for each forecast so 0, 1, and 2)
dateTimeNowString = dateTimeNowString.AddSeconds(amountOfSecondsElapsedSince1970).AddHours(hour).ToLocalTime();
// This is the dateTime
string dateRealWeatherForecastTimee = dateTimeNowString.ToString("yyyyMMddhh");
return dateRealWeatherForecastTimee;
}
Nothing seems to work.
Update
I tried the following line on a new asp.net core console project (rather than the project I'm working on):
string dateTimeNowPlusForecaseHour = DateTime.Now.AddHours(hour).ToString("yyyyMMddhh");
That works! But why doesn't it work for the project I'm working on?
Update2.0:
When I view my timezone of the project, I get GMT which is wrong. When I create a new asp.net core console project and view the timezone, I get w. europe, which gives me the correct time... Why is the timezone wrong? Shouldn't that be correct automatically?
DateTime.Now returns the current time and day. The struct it returns
can be stored as a field or property in a class. We look into this
property and its implementation—where it accesses the operating system
for the current time.
string dateTimeNowPlusForecaseHour = DateTime.Now.ToString("yyyyMMddHH");
This screenshot is taken from here. And I've used almost all of these, which means these are tested and should definitely work. If you still get incorrect hour, please check the time-zone of the server where you're hosting your application.
I would like to define a datetime type variable that is a result of a simple arithmetic operation between datetime type variables.
I've defined:
datetime duration = ( TimeCurrent() - OrderOpenTime() );
datetime TmStop = StringToTime( "1970.01.01 16:00" );
but when I call it in some other arithmetic operation or generally in code like this
ExitBuy_H1 = ( duration > TmClose && ...
or this
text[3]= "Duration: " + TimeToStr( duration, TIME_MINUTES );
it doesn't work.
TmStop instead works fine.
Does anyone know why?
datetime is a simple integer, number of seconds passed since 1970.01.01 00:00. duration in your example is also in seconds, even though it is datetime formated, when you need it in minutes, divide by 60. TmClose from your example means 16*60*60 seconds and you can compare that integer with any other int of course, but what might be the reason for that?
if you hold you position more then 16 hours, then duration > TmClose is true. if you want to convert difference in seconds (duration) into time, then you will have time converted from 1970.01.01 00:00 + duration seconds.
Anyway it is not clear what is your goal in doing this calculations? if you want to make sure that you hold that particular position more then x hours, then simple bool holdMoreThanXHours = TimeCurrent()-OrderOpenTime()>x*PeriodSeconds(PERIOD_H1), and do not forget to reselect each ticket if you have several ones in open
Fact A) the code, as-is, absolutely out of any question works.
//+------------------------------------------------------------------+
//| Test_StackOverflow.mq4 |
//+------------------------------------------------------------------+
#property strict
void OnStart() {
datetime duration = ( TimeCurrent() - OrderOpenTime() );
string txt = "Duration: " + TimeToStr( duration, TIME_MINUTES );
}
//+------------------------------------------------------------------+
0 error(s), 0 warning(s), compile time: 2000 msec 1 1
Fact B) the full MCVE-context of the code, as-is, is missing.
StackOverflow requires users to post a complete MCVE-representation of the problem. This requirement was not met in the original post.
While the datetime and int data-types are mutually interchangeable, the problem does not seem to be hidden in this intrinsic "duality" of a value representation, but must be somewhere else.
The main suspects for Why? are:
variable definition was masked by another variable having the same name
variable scope-of-definition was exceeded ( asking a variable outside of it's scope )
db.Pool-operations were not preceded by OrderSelect()
Using JDK 1.8
I have Time in ms for a day (not since 1970) and I have a Date how do I add the two and create a datetime.
Thanks
Tried #Kikos soln does not produce correct result:
Somehow my orig time 930 hrs in this case changes to 9:40, the orig date itself should not have any time gets time (??) - so the addition math fails.
String testdate = "2015/10/25";
Date date = new SimpleDateFormat("yyyy/mm/dd").parse(testdate);
String timehrs= "930";
long ltime = Long.parseLong("930");
long hoursAsSeconds = (ltime / 100) * 60 * 60;
long minsAsSeconds = (ltime % 100) * 60;
long secondsOfDay = hoursAsSeconds + minsAsSeconds;
System.out.println("testdate : "+ testdate +", timehrs: "+timehrs+" ,secondsOfDay: "+secondsOfDay);
System.out.println("Orig Date time formatted: "+ new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(date));
Date dt = new Date(date.getTime() + secondsOfDay*1000);
System.out.println("New Date : "+ new SimpleDateFormat("yyyy-mm-dd hh:mm:ss").format(dt);
testdate : 2015/10/25, timehrs: 930, secondsOfDay: 34200
Orig Date time formatted: 2015-10-25 12:10:00
New Date : 2015-40-25 09:40:00
Expected : 2015-10-25 09:30:00
Based on below by #Basil Bourque
long nanosOfDay = TimeUnit.MILLISECONDS.toNanos( secondsOfDay*1000 );
LocalTime lt = LocalTime.ofNanoOfDay( nanosOfDay );
ZoneId z = ZoneId.systemDefault();
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
System.out.println("ZonedDateTime zdt: "+ zdt);
ZonedDateTime zdt: 2015-10-25T09:30-07:00[America/Los_Angeles]
This is the correct answer: 2015-10-25T09:30
Question is convoluted
You say you have time of day as a count of milliseconds since midnight (apparently). Yet 930 would mean the time 00:00:00.930, not 09:30:00 as shown in your example data. I will follow your text rather than your example data.
java.time
You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes. Forget you ever heard of java.util.Date and .Calendar.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );
ISO 8601
The java.time classes use the ISO 8601 standard by default when parsing/generating strings representing date-time values. To make your input string standard, replace those slash characters with hyphens.
String input = "2015/10/25".replace( "/" , "-" );
LocalDate ld = LocalDate.parse( input );
By the way, this whole scheme you have been assigned is awkward, error-prone, and needlessly complicated. To serialize a date-time value for communication between systems, use the ISO 8601 string formats.
LocalTime
You say you have a count of milliseconds to represent the time of day as a count from midnight.
The LocalTime class offers factory methods to instantiate based on a duration of whole seconds and of nanoseconds. To get nanoseconds, simply multiply your milliseconds by one thousand. Better yet, let the TimeUnit enum do the work and make your code more self-documenting.
long millisOfDay = Long.parseLong( "930" );
long nanosOfDay = TimeUnit.MILLISECONDS.toNanos( millisOfDay ); // Same effect as: ( millisOfDay * 1_000L )
LocalTime lt = LocalTime.ofNanoOfDay( nanosOfDay );
ZonedDateTime
Now combine these two Local… objects along with a time zone to determine a point on the timeline. Was this date and time meant to be a moment in Montréal Québec, Paris France, Kolkata India, or Aukland New Zealand?
ZoneId z = ZoneId.of( "Pacific/Auckland" );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
See live code in IdeOne.com.
ld.toString(): 2015-10-25
lt.toString(): 00:00:00.930
zdt.toString(): 2015-10-25T00:00:00.930+13:00[Pacific/Auckland]
LocalDateTime
If your data came with no information about time zone, and you cannot safely assume the intended time zone by your business scenario, you are left with no better option than combining into a LocalDateTime object. But keep in mind that this value is ambiguous. This value is not a point on the timeline. This value represents potential points on the timeline which can only be determined with a time zone assigned for ZonedDateTime or a offset-from-UTC assigned for OffsetDateTime.
LocalDateTime ldt = LocalDateTime.of( ld , lt );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
Java SE 8 and SE 9 and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
See How to use….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
something like:
Date dt = new Date(System.currentTimeMillis() + ms);
or
Date otherDate(....);
Date dt = new Date(otherDate.getTime() + ms);
BACKGROUND (ok to ignore/skip):
I feel like there should be a better way to do what I'm doing, but I don't know what it is and I think my solution works, but I thought I'd ask in case there is something more elegant or faster or whatever.
I am developing a web page with MS Razor MVC which uses Html.DropDownList, which gives a pick list UI control which maps choices as display strings to integer ID codes. (I don't think I can have it map strings to DateTime values.)
But in a couple of cases, I want to choose from dates that are stored as DateTime objects. I realize I could make yet another table in memory that relates ID codes to DateTime values, but I thought instead (and also because I think I may want to encode dates as ints for yet another workaround of web page annoyances), I would encode the date as an int.
PROBLEM:
How best to convert the date of a DateTime object as an int value, and then later set a DateTime's date back to that date from the encoded int. The main ugliness of my solution is that DateTime provides a read-only DayOfYear function, but no way I know of to set a date back to (Date, DayOfYear), so I wrote a method with a loop, which is cute but probably slowish.
MY CURRENT (OK) SOLUTION:
public int encodeDate(DateTime date)
{
return ((date.Year - 2012) * 400) + date.DayOfYear;
}
public DateTime decodeDateCode(int dateCode)
{
int year = (dateCode / 400) + 2012;
int day = dateCode % 400;
// MS DateTime doesn't provide a direct reverse conversion for DayOfYear, so find it:
int month = 1;
int mThresh = DateTime.DaysInMonth(year, month);
while (day > mThresh)
{
day -= mThresh;
month++;
mThresh = DateTime.DaysInMonth(year, month);
}
DateTime dateValue = new DateTime(year, month, day);
return dateValue;
}
Ho about to format the timestamp as POSIX time (POSIX time / Unix time, see http://en.wikipedia.org/wiki/Unix_time)?
I had a similar problem myself and found a great solution here: Convert a Unix timestamp to a .NET DateTime
From the link:
DateTime ConvertFromUnixTimestamp(double timestamp)
{
}
double ConvertToUnixTimestamp(DateTime date)
{
}