DateTime.Date (long value) - vb.net

I have spent quite a few hours and still unable to understand this:
Dim unix_time_at_midnight As Long
DateTime.DateFormat = "MM/dd/yyyy"
unix_time_at_midnight = DateTime.DateParse(DateTime.Date(unix_time*1000))/1000
where both unix_time_at_midnight and unix_time are long values. I understand DateTime.DateParse excepts a String and converts it to DateTime. What is (DateTime.Date(unix_time*1000))/1000 returning and what is its equivalent in Java? The requirement is to get the number of seconds since GMT midnight and I have successfully implemented it in Java. However, I would like to understand this particular line of code written in VB.net
EDIT: This method was written in Basic4Android and probably constitutes more of its libraries then vb.net. However, I have looked into each for details but unable to understand. Would appreciate if you could elaborate. Please see the links.

Take this:
DateTime.Date(unix_time*1000)
The documentation says:
Date (Ticks As Long) As String
Returns a string representation of the date (which is stored as ticks).
The date format can be set with the DateFormat keyword.
So that part returns a string representing the date.
It then uses DateTime.DateParse, which is documented as:
DateParse (Date As String) As Long
Parses the given date string and returns its ticks representation.
Taken together, this appears to take the ticks, multiplied by 1000, converted to a string that doesn't contain hour information which is parsed back to ticks which are divided by 1000.
The important thing to note is that the DateFormat set on the line before contains only the formatting for the date, no hours/minutes/seconds and smaller units of time exist in it. This means that the string returned essentially represents midnight of that date.

Related

Converting one unknown DatePattern to a known pattern

I get the user machine's date pattern using this:
Dim sysFormat As String = CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern
so for example it comes as M/d/yy but in my program I want to parse them in a M/d/yyyy format. But they could even have some other format, we don't know what format. It is ALWAYS gonna be US English tho.
So is there a way to automatically convert whatever it is to the M/d/yyyy format ? or do I have to manually do some string processing code and split the string to different parts for day,month, year?
Have you tried formatting your String to a Datetime object and then parsing using a specific formatter?
Dim myDate As DateTime = DateTime.ParseExact(sysFormat, "M/d/yyyy",
System.Globalization.CultureInfo.InvariantCulture)
And your new String (the one that's formatted) is:
Dim formattedStringDate As String = myDate.ToString("M/d/yyyy")
The requirements you have seem quite specific. You could use DateTime.TryParseExact to try parsing a few valid formats and check whether any results in a valid date. With new C# features you could even get rid of the extra out-parameter declaration. For example:
DateTime.TryParseExact(dateTime,
"M/d/yy",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
DateTime out dt);

convert date in 2015-05-09T09:00:12.123462000 to unix timestamp in hive

I want to convert the date which is in '2015-05-09T09:00:12.123462000' format to the unix timestamp in hive. The UNIX_TIMESTAMP('2015-05-09T09:00:12.123462000') doesn't work. I am not sure how i can convert this. I need this to compare two dates in different format. I am converting both the dates to unix timestamp but this fails. can someone please help with this.
Thanks
Your input uses the full ISO 8601 format, with a "T" between date and time, and fractional seconds. Hive expects an SQL format (i.e. with a space between date and time) as seen in java.sql.Timestamp and ODBC, with or without fractional seconds, as stated in the Hive documentation.
Just apply some very elementary string massaging -- then "cast" the String to a Hive Timestamp. And pleeease forget that lame roundtrip to and from UNIX_TIMESTAMP:
cast(regexp_replace('2015-05-09T09:00:12.123462000', 'T',' ') as Timestamp)
The Answer by Samson Scharfrichter is correct and should be accepted. I'll just add some words about java.time types.
Converting between String ↔ java.time.Instant
The java.time classes supplant the troublesome old legacy date-time classes such as java.sql.Timestamp.
The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Your input string complies with the ISO 8601 standard. The java.time classes use ISO 8601 formats by default when parsing/generating strings that represent date-time values. So no need to specify a formatting pattern. You can directly parse your string as an Instant object.
Your input string lacks an indication of offset-from-UTC or time zone. If it was intended to be in UTC, append a Z for Zulu which means UTC.
Instant instant = Instant.parse( "2015-05-09T09:00:12.123462000" + "Z" );
You can generate such a string, merely call toString. The default formatter used by toString prints the decimal fraction in groups of three digits as needed. In this example the last three digits are zeros so they are omitted.
String output = instant.toString();
2015-05-09T09:00:12.123462Z
To make this into SQL-style string expected by Hive, replace the T with a SPACE and remove the Z.
String inputForHive = output.replace( "T" , " " ).replace( "Z" , "" );
2015-05-09 09:00:12.123462
Conversion from numbers
Hive also provides for conversions from:
integer numberCount of whole seconds from the Unix/Posix epoch of beginning of 1970 UTC (1970-01-01T00:00:00Z).
floating-point numberSame as above but with a fractional second in up to nanoseconds resolution.
The second one I suggest you avoid. The floating-point types such as float, Float, double, and Double in Java purposely trade off accuracy for faster execution time. This often results in extraneous digits at the end of your decimal fraction. If you need fractional second, stick with the String type & Instant object.
The first one can easily be obtained from an Instant by calling the getEpochSecond method. Of course this means data loss as this method leaves behind any fractional second.
long secondsSinceEpoch = instant.getEpochSecond();
Going the other direction.
Instant instant = Instant.ofEpochSecond( secondsSinceEpoch );
Comparing
Once you have your Instant objects, you can compare with methods such as compareTo, equals, isBefore, isAfter.
Boolean happenedBefore = thisInstant.isBefore( thatInstant );
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old date-time classes such as java.util.Date, .Calendar, & java.text.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.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (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.
If available you can simply use the following syntax
1) check whether what UDFs are available in your hive install?
show functions;
2) if seen from_unixtime() function then:
from_unixtime(your_timestamp_field)
This will solve the problem!
Please add comments, if you like my answer!

Enter date into function without quotes, return date

I'm trying to write a function of this form:
Function cont(requestdate As Date)
cont = requestdate
End Function
Unfortunately, when I enter =cont(12/12/2012) into a cell, I do not get my date back. I get a very small number, which I think equals 12 divided by 12 divided by 2012. How can I get this to give me back the date? I do not want the user to have to enter =cont("12/12/2012").
I've attempted to google for an answer, unfortunately, I have not found anything helpful. Please let me know if my vocabulary is correct.
Let's say my user pulled a report with 3 columns, a, b and c. a has beginning of quarter balances, b has end of quarter balances and c has a first and last name. I want my user to put in column d: =cont(a1,b1,c1,12/12/2012) and make it create something like:
BOQ IS 1200, EOQ IS 1300, NAME IS EDDARD STARK, DATE IS 12/12/2012
So we could load this into a database. I apologize for the lack of info the first time around. To be honest, this function wouldn't save me a ton of time. I'm just trying to learn VBA, and thought this would be a good exercise... Then I got stuck.
Hard to tell what you are really trying to accomplish.
Function cont(requestdate As String) As String
cont = Format(Replace(requestdate, ".", "/"), "'mm_dd_YYYY")
End Function
This code will take a string that Excel does not recognize as a number e.g. 12.12.12 and formats it (about the only useful thing I can think of for this UDF) and return it as a string (that is not a number or date) to a cell that is formatted as text.
You can get as fancy as you like in processing the string entered and formatting the string returned - just that BOTH can never be a number or a date (or anything else Excel recognizes.)
There is no way to do exactly what you're trying to do. I will try to explain why.
You might think that because your function requires a Date argument, that this somehow forces or should force that 12/12/2012 to be treated as a Date. And it is treated as a Date — but only after it's evaluated (only if the evaluated expression cannot be interpreted as a Date, then you will get an error).
Why does Excel evaluate this before the function receives it?
Without requiring string qualifiers, how could the application possibly know what type of data you intended, or whether you intended for that to be evaluated? It could not possibly know, so there would be chaos.
Perhaps this is best illustrated by example. Using your function:
=Cont(1/1/0000) should raise an error.
Or consider a very simple formula:
=1/2
Should this formula return .5 (double) or January 2 (date) or should it return "1/2" (string literal)? Ultimately, it has to do one of these, and do that one thing consistently, and the one thing that Excel will do in this case is to evaluate the expression.
TL;DR
Your problem is that unqualified expression will be evaluated before being passed, and this is done to avoid confusion or ambiguity (per examples).
Here is my method for allowing quick date entry into a User Defined Function without wrapping the date in quotes:
Function cont(requestdate As Double) As Date
cont = CDate((Mid(Application.Caller.Formula, 7, 10)))
End Function
The UDF call lines up with the OP's initial request:
=cont(12/12/2012)
I believe that this method would adapt just fine for the OP's more complex ask, but suggest moving the date to the beginning of the call:
=cont(12/12/2012,a1,b1,c1)
I fully expect that this method can be optimized for both speed and flexibility. Working on a project now that might require me to further dig into the speed piece, but it suits my needs in the meantime. Will update if anything useful turns up.
Brief Explanation
Application.Caller returns a Range containing the cell that called the UDF. (See Caveat #2)
Mid returns part of a string (the formula from the range that called the UDF in this case) starting at the specified character count (7) of the specified length (10).
CDate may not actually be necessary, but forces the value into date format if possible.
Caveats
This does require use of the full dd/mm/yyyy (1/1/2012 would fail) but pleasantly still works with my preferred yyyy/mm/dd format as well as covering some other delimiters. dd-mm-yyyy or dd+mm+yyyy would work, but dd.mm.yyyy will not because excel does not recognize it as a valid number.
Additional work would be necessary for this to function as part of a multi-cell array formula because Application.Caller returns a range containing all of the associated cells in that case.
There is no error handling, and =cont(123) or =cont(derp) (basically anything not dd/mm/yyy) will naturally fail.
Disclaimers
A quick note to the folks who are questioning the wisdom of a UDF here: I've got a big grid of items and their associated tasks. With no arguments, my UDF calculates due dates based on a number of item and task parameters. When the optional date is included, the UDF returns a delta between the actual date and what was calculated. I use this delta to monitor and calibrate my calculated due dates.
All of this can absolutely be performed without the UDF, but bulk entry would be considerably more challenging to say the least.
Removing the need for quotes sets my data entry up such that loading =cont( into the clipboard allows my left hand to F2/ctrl-v/tab while my right hand furiously enters dates on the numpad without need to frequently (and awkwardly) shift left-hand position for a shift+'.

TimeSpan not calculating

I am trying to calculate create a time remaining calculator in VB.NET and it won't let me and I can't seem to figure out why. Here is my code
Dim PrefendinedDateTime As DateTime = "3:00:00"
Dim TimeNow As DateTime = DateTime.Now
Dim ElapsedTime As TimeSpan = (TimeNow - frmStartDateTime)
Dim TimeRemaining As TimeSpan = PrefendinedDateTime - New DateTime(ElapsedTime.Ticks)
txtTimeRemaining.Text = New DateTime(TimeRemaining.Ticks).ToString("HH:mm:ss")
I get this error message:
Ticks must be between DateTime.MinValue.Ticks and DateTime.MaxValue.Ticks.
Parameter name: ticks
Not quite sure what this means
You cannot cast a timespan to a date, because those are different ticks. What you need is this:
txtTimeRemaining.Text = TimeRemaining.ToString("g")
or this:
txtTimeRemaining.Text = TimeRemaining.ToString("hh\:mm\:ss")
Notice how format string is different for TimeSpan, compared to formatting a date time, for example, and that : now requires escaping. This is explained in detail in below link #2.
References:
Standard TimeSpan Format Strings # MSDN
Custom TimeSpan Format Strings # MSDN
Let's stop here for a second, while I try to explain why it did not work for you. Forget about ticks, think in seconds, because it's a measurable interval, that's easy to get a grasp on. Suppose you time interval is a second. Now you are trying to create a date, passing one second into it. What do you expect to get? 1 second AD, i.e. 1st year, 1st month etc.? Fair enough.
Suppose now you have an interval of minus 1 second (yes, intervals can be negative). You would think it's 1 second BC, right? Unfortunately, negative dates in .NET are not allowed.
As a general rule of thumb, intervals of time (represented in .NET by a TimeSpan), and points in time (represented by a DateTime) should be treated separately, because they are logically different entities. There is one-way relation though, i.e. two dates can represent a TimeSpan. However, a TimeSpan does not represent two dates. In fact, no matter how many TimeSpans you have, you will never be able to relate them to any point in time.

How to change Time Format in VB.NET from 24 to 12?

I am using these codes for displaying time in VB.NET
it shows up in 24 hours format besides i need it in 12 hours format
System.DateTime.Now.Hour
System.DateTime.Now.Minute
System.DateTime.Now.Second
example:
14:12:42
I need it as :
02:12:42
thanks.
Use String.Format. For example:
String.Format("{0:T}", System.DateTime.Now) //02:12:42 PM
String.Format("{0:hh:mm:ss}", System.DateTime.Now) //02:12:42
String.Format("{0:hh:mm:ss tt}", System.DateTime.Now) //02:12:42 PM
Also, this website to be very helpful in summarizing the various ways you can use String.Format. Keep in mind the culture can make a difference on non-custom formats. The first example above using T (Long Time format) works on my US-based PC just fine. But if you say:
String.Format(System.Globalization.CultureInfo.InvariantCulture, _
"{0:T}", System.DateTime.Now)
You end up with 14:12:42. The latter two examples are custom formats and are not affected by culture.
When using DateTime objects you can actually use the ToString() method and set your format inside it.
string currentTime = System.DateTime.Now.ToString("hh:mm:ss");
Check this msdn article out for more clarity:
http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Use the appropriate format string for display.
string formatted = myDateTime.ToString("hh:mm:ss");
I have used a custom format string in this case.
1-Use regex to get first two characters of that string ie from 23:11:59 get 23
2-convert this number to integer type
3-now check it if it is not greater than 12 and if it is subtract 12 from it and by using string.replace replace the old value.
Try This...
Dim CurTime As String
CurTime = TimeOfDay.ToString("h:mm:ss tt")