Trying to find out how to convert local time into universal time (java), all the answers I found don't seem to work for me - j#

I have this (the code), and the answer (the hour) should be 11.00
The problem is that the answers I am getting are completely wrong;
(wed april 10 13:09:04 ), todays date ...
Also, i guess it needs the lat and long as well, how must I parse this ?
String dateString = 26 + "-" + 4 + "-" + 1926 + " " + 5 + ":00:00 " ;
SimpleDateFormat f = new SimpleDateFormat( dateString );
f.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println( (new Date()) );
String dd = f.format(new Date());
System.out.println( " " ) ;

I've got ;
String d = LocalDateTime
.parse(
"26-04-1926 05:00:00",
DateTimeFormatter.ofPattern( "dd-MM-uuuu HH:mm:ss" )
)
.atOffset(
ZoneOffset.UTC
)
.toString();
System.out.println( d ) ;
But the output is '1926-04-26T05:00Z'
while the hour should be 11:00
Where did I went wrong?
Also, can I get the output (the hour) as an int?

Related

VBS to format date Date: Tue, 18 Nov 2022 15:57:11 +0000 [duplicate]

This question already has an answer here:
Format current date and time in VBScript
(1 answer)
Closed 8 months ago.
So I am trying to format my date properly in a readable format.
Here is my code.
WScript.Echo(DateDiff("s", "01/01/1970 00:00:00", Now()))
Function sprintf(sFmt, aData)
With CreateObject("System.Text.StringBuilder")
.AppendFormat_4 sFmt, (aData)
sprintf = .ToString()
.Length = 0
End With
End Function
Dim CurrTime : CurrTime = Now()
Dim Elapsed : Elapsed = Timer()
Dim MilliSecs : MilliSecs = Right("000" & Int((Elapsed - Int(Elapsed)) * 1000), 3)
'echo "Date: " . date("D, d M Y H:i:s O");
'Date: Tue, 18 Nov 2014 15:57:11 +0000
WScript.Echo "Date: ", sprintf( "{0:yyyy/MM/dd HH:mm:ss}", Array(CurrTime)) & "." & MilliSecs
The output i am trying to achieve is this
Date: Tue, 18 Nov 2022 15:57:11 +0000
But i am missing allot
Function sprintf(sFmt, aData)
With CreateObject("System.Text.StringBuilder")
.AppendFormat_4 sFmt, (aData)
sprintf = .ToString()
.Length = 0
End With
End Function
Dim CurrTime : CurrTime = Now()
WScript.Echo WeekdayName(Weekday(Now()),True) & ", " & Day(Now()) & " " & MonthName(Month(Now()),True) & " " & sprintf( "{0:yyyy HH:mm:ss}", Array(CurrTime)) & " +0000"
Figured out a way to get the output i wanted.

Kotlin: Getting the difference betweeen two dates (now and previous date)

Sorry if similar questions have been asked too many times, but it seems that there's one or more issues with every answer I find.
I have a date in the form of a String: Ex.: "04112005"
This is a date. 4th of November, 2005.
I want to get the difference, in years and days, between the current date and this date.
The code I have so far gets the year and just substracts them:
fun getAlderFraFodselsdato(bDate: String): String {
val bYr: Int = getBirthYearFromBirthDate(bDate)
var cYr: Int = Integer.parseInt(SimpleDateFormat("yyyy").format(Date()))
return (cYr-bYr).toString()
}
However, naturally, this is quite innacurate, since the month and days aren't included.
I've tried several approaches to create Date, LocalDate, SimpleDate etc. objects and using these to calcualate the difference. But for some reason I haven't gotten any of them to work.
I need to create a Date (or similar) object of the current year, month and day. Then I need to create the same object from a string containing say, month and year (""04112005""). Then I need to get the difference between these, in years, months and days.
All hints are appreciated.
I would use java.time.LocalDate for parsing and today along with a java.time.Period that calculates the period between two LocalDates for you.
See this example:
fun main(args: Array<String>) {
// parse the date with a suitable formatter
val from = LocalDate.parse("04112005", DateTimeFormatter.ofPattern("ddMMyyyy"))
// get today's date
val today = LocalDate.now()
// calculate the period between those two
var period = Period.between(from, today)
// and print it in a human-readable way
println("The difference between " + from.format(DateTimeFormatter.ISO_LOCAL_DATE)
+ " and " + today.format(DateTimeFormatter.ISO_LOCAL_DATE) + " is "
+ period.getYears() + " years, " + period.getMonths() + " months and "
+ period.getDays() + " days")
}
The output for a today of 2020-02-21 is
The difference between 2005-11-04 and 2020-02-21 is 14 years, 3 months and 17 days
It Works Below 26 API level
There are too many formates of dates you just enter the format of date and required start date and end date. It will show you result. You just see different date formate hare and here if you need.
tvDifferenceDateResult.text = getDateDifference(
"12 November, 2008",
"31 August, 2021",
"dd MMMM, yyyy")
General method to calculate date difference
fun getDateDifference(fromDate: String, toDate: String, formater: String):String{
val fmt: DateTimeFormatter = DateTimeFormat.forPattern(formater)
val mDate1: DateTime = fmt.parseDateTime(fromDate)
val mDate2: DateTime = fmt.parseDateTime(toDate)
val period = Period(mDate1, mDate2)
// period give us Year, Month, Week and Days
// days are between 0 to 6
// if you want to calculate days not weeks
//you just add 1 and multiply weeks by 7
val mDays:Int = period.days + (period.weeks*7) + 1
return "Year: ${period.years}\nMonth: ${period.months}\nDay: $mDays"
}
For legacy Date functions below api 26 without running desugaring with Gradle plugin 4.0, java.time.* use:
fun getLegacyDateDifference(fromDate: String, toDate: String, formatter: String= "yyyy-MM-dd HH:mm:ss" , locale: Locale = Locale.getDefault()): Map<String, Long> {
val fmt = SimpleDateFormat(formatter, locale)
val bgn = fmt.parse(fromDate)
val end = fmt.parse(toDate)
val milliseconds = end.time - bgn.time
val days = milliseconds / 1000 / 3600 / 24
val hours = milliseconds / 1000 / 3600
val minutes = milliseconds / 1000 / 3600
val seconds = milliseconds / 1000
val weeks = days.div(7)
return mapOf("days" to days, "hours" to hours, "minutes" to minutes, "seconds" to seconds, "weeks" to weeks)
}
The above answers using java.time.* api is much cleaner and accurate though.

Generate a list of the week/year according ISO 8601

I try to generate a list of days with their week number (defined by ISO 8601) accordingly :
mydate='2012-12-25 02:26:55.983'
for (i=1;i<365;i++)
{
mydateAsDate=new Date().parse('yyyy-MM-dd H:mm:ss.S',mydate)+i;
println 'Week ' + mydateAsDate.format('w') + ' => ' + mydateAsDate.format('dd.MM.yyyy');
}
This works but I would like to get the year also like this:
Week 1-2013
I can't figure out which year information I should take.
Any idea?
As Jon Skeet said, I'd recommend using Joda-Time.
If you do, the following should fix your issues:
mydate= new DateTime(2012,12,25)
yearLater = myDate.plusYears(1)
while(myDate < yearLater){
println "Week ${myDate.weekOfWeekyear} - ${myDate.year}"
myDate = myDate.plusDays(1)
}
Not sure I understand, but you mean like:
String startDateString = '2012-12-25 02:26:55.983'
Date startDate = Date.parse( 'yyyy-MM-dd H:mm:ss.S', startDateString )
(1..364).each { i ->
println( (startDate++).format( "dd.MM.yyyy : 'Week' w'-'yyyy" ) )
}
I got it : SimpleDateFormat delivers the right week year information when using the YYYY format
thus this is only available in java 1.7
thanks for your responses though !
cheers

Convert function to Classic ASP

I am using a mailing list program which inserts a date into a web link that is "encoded" so it can't be changed or edited by users.
The format is described as follows:
An eight character string, AABBCCDD,where:
Year = 1980 + HexToInt(BB) / 3
Month = HexToInt(CC) / 7 - 21
Day = HexToInt(DD) / 7 - 5
There is also a checksum included to avoid casual modification:
AA = IntToHex(Year + Month + Day mod 200)
For example 2660BDAF would refer to 20 June, 2012.
Can you help me convert the following to Classic ASP:
CodedDateStr = Request.querystring("Exp")
AYear = 1980 + HexToInt(CodedDateStr[3] + CodedDateStr[4]) / 3
AMonth = HexToInt(CodedDateStr[5] + CodedDateStr[6]) / 7 - 21
ADay = HexToInt(CodedDateStr[7] + CodedDateStr[8]) / 7 - 5
ACheckSum = AYear + AMonth + ADay mod 200
if ACheckSum <> HexToInt(CodedDateStr[1] + CodedDateStr[2]) then
ValidDate = 0
else
ValidDate = 1
end if
AExpiryDate = EncodeDate(ADay, AMonth, AYear)
if Date() > AExpiryDate then
ExpiredOffer = 1
else
ExpiredOffer = 0
end if
....
It looks like the HexToInt equivalent is clng("&h" & hexnumber)
I'm not sure about EncodeDate, i hope it is not something cludgy like CDate(AMonth + "/" + ADay + "/" + AYear)
CLng("&h" & hexnumber) looks like a good method for HexToInt.
For EncodeDate, look at the DateSerial function, which takes a year, month, and day, and returns a Date value.

VBScript How can I Format Date?

I want the date to look like MM-DD-YYYY instead of MM/DD/YYYY.
0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm
d=CDate("2010-02-16 13:45")
document.write(FormatDateTime(d) & "<br />")
document.write(FormatDateTime(d,1) & "<br />")
document.write(FormatDateTime(d,2) & "<br />")
document.write(FormatDateTime(d,3) & "<br />")
document.write(FormatDateTime(d,4) & "<br />")
If you want to use another format you will have to create your own function and parse Month, Year, Day, etc and put them together in your preferred format.
Function myDateFormat(myDate)
d = TwoDigits(Day(myDate))
m = TwoDigits(Month(myDate))
y = Year(myDate)
myDateFormat= m & "-" & d & "-" & y
End Function
Function TwoDigits(num)
If(Len(num)=1) Then
TwoDigits="0"&num
Else
TwoDigits=num
End If
End Function
edit: added function to format day and month as 0n if value is less than 10.
Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.
Thus:
Function timeStamp()
Dim t
t = Now
timeStamp = Year(t) & "-" & _
Right("0" & Month(t),2) & "-" & _
Right("0" & Day(t),2) & "_" & _
Right("0" & Hour(t),2) & _
Right("0" & Minute(t),2) ' '& _ Right("0" & Second(t),2)
End Function
The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.
If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use
Replace(FormatDateTime(d,2),"/","-")
'for unique file names I use
Dim ts, logfile, thisScript
thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension
ts = timeStamp
logfile = thisScript & "_" & ts
' ======
Function timeStamp()
timeStamp = Year(Now) & "-" & _
Right("0" & Month(Now),2) & "-" & _
Right("0" & Day(Now),2) & "_" & _
Right("0" & Hour(Now),2) & _
Right("0" & Minute(Now),2) ' '& _ Right("0" & Second(Now),2)
End Function
' ======
This snippet also solve this question with datePart function. I've also used the right() trick to perform a rpad(x,2,"0").
option explicit
Wscript.Echo "Today is " & myDate(now)
' date formatted as your request
Function myDate(dt)
dim d,m,y, sep
sep = "-"
' right(..) here works as rpad(x,2,"0")
d = right("0" & datePart("d",dt),2)
m = right("0" & datePart("m",dt),2)
y = datePart("yyyy",dt)
myDate= m & sep & d & sep & y
End Function
Although answer is provided I found simpler solution:
Date:
01/20/2017
By doing replace
CurrentDate = replace(date, "/", "-")
It will output:
01-20-2017
For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.
Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)
Which will result in 11-22-2019 (depending on the current date)