UTC_TIMESTAMP() to user defined timezone? - unix-timestamp

I am storing timestamps in my db using UTC_TIMESTAMP().
I want to output them based on user selected timezone. I tried writing a small function to do this, however, it does not output correctly.
// Date/time converter
function convertTZ($date, $tz, $tzFormat)
{
$date = new DateTime($date);
$date->setTimezone(new DateTimeZone($tz));
return $date->format($tzFormat);
}
echo $_SESSION['dtCurrLogin'].'<br />';
echo convertTZ($_SESSION['dtCurrLogin'], 'UTC', 'F j, Y # g:i:s a e');
dtCurrLogin from db = 2013-09-12 01:23:45
the above outputs :
2013-09-12 01:23:45
September 12, 2013 # 5:23:45 am UTC
Obviously this is not correct as I went from UTC to UTC so they should be equal. If I change to output EST then it shows 1:23:45 am, but of course that would not be right either.

Didn't realize I needed to specify incoming timezone... using the following worked for me...
function convertTZ($date_time, $from_tz, $to_tz, $format_tz)
{
$time_object = new DateTime($date_time, new DateTimeZone($from_tz));
$time_object->setTimezone(new DateTimeZone($to_tz));
return $time_object->format($format_tz);
}

Related

TypeORM : How to search for a range of Date in PostgresSQL?

consider an ISO8601 date
and want to do a query using Typeorm and PostgreSQL
if (orderInput.begining && orderInput.ending)
query.andWhere(`order.createdAt
BETWEEN to_timestamp(${orderInput.begining} / 1000 )
AND to_timestamp(${orderInput.ending} / 1000 );
`);
These are my argument:
"2010-12-24T21:32:33.477Z"
"2019-12-24T21:32:33.477Z"
and this is the underhood query and the err :
query failed: SELECT DISTINCT "distinctAlias"."order_id" as "ids_order_id" FROM (SELECT "order"."id" AS "order_id", "order"."createdAt" AS "order_createdAt"
FROM "order" "order" INNER JOIN "ware" "ware" ON "ware"."id"="order"."wareId" WHERE "order"."organizationId" = $1 AND "order"."createdAt"
BETWEEN Wed Dec 25 2019 01:02:33 GMT+0330 (Iran Standard Time)
AND Wed Dec 25 2019 01:02:33 GMT+0330 (Iran Standard Time) ;) "distinctAlias" ORDER BY "order_id" ASC LIMIT 25 -- PARAMETERS: ["8fd87ced-eb58-4460-b74e-d5a2b1491622"]
error: { error: syntax error at or near "Dec"
I guess it's because of that the arguments are not taken wraped in ' ' (qoutes)
I don't know how to pass the arguments to typescript as standard ISO8606 Date(typescript) with ' '(qoutes) to be then passed to PostgreSQL
My solution as of now(2021-05-26) using Between of TypeORM (docs):
const orders = await this.orderRepo.find({
where: {
createdAt: Between(
new Date(orderInput.begining).toISOString(),
new Date(orderInput.ending)).toISOString(),
),
},
skip: skip || 0,
take: take || 10,
});
Both Typescript And PostgreSQL know ISO8601 well and there is no need to to_timestamp() for PostgreSQL.
So this works like a chram:
if (orderInput.begining && orderInput.ending)
query.andWhere(
`"order"."createdAt"
BETWEEN :begin
AND :end`
,{ begin: orderInput.begining, end: orderInput.ending);
NOTE: in JavaScript, you can easily make a ISO8601 standard Date in this way:
const date = new Date(2020,2,2)
const iso = date.toISOString()
Try this:
await this.YOUR_REPOSITORY
.createQueryBuilder("order")
.where('order.createdAt BETWEEN :startDate AND :endDate', { startDate: orderInput.begining, endDate: orderInput.ending })
.getMany();

How to get the list of timezones supported by PostgreSQL?

The question is pretty self-explanatory. I found this documentation here:
https://www.postgresql.org/docs/current/view-pg-timezone-names.html
However, it does not really mention how to get a list of all the supported timezones. How can I do this?
You may try selecting from the view pg_timezone_names, as the documentation says:
The view pg_timezone_names provides a list of time zone names that are recognized by SET TIMEZONE, along with their associated abbreviations, UTC offsets, and daylight-savings status.
Try the following query:
SELECT
name,
abbrev,
utc_offset,
is_dst
FROM pg_timezone_names;
The answer from Tim was excellent.
For whatever reason my Postgres DB also contained a bunch of fluff with the prefix "posix/" and I also needed these in alphabetical order to use on a website, so I did this:
SELECT
name,
abbrev,
utc_offset,
is_dst
FROM pg_timezone_names
WHERE name !~ 'posix'
ORDER BY name asc;
I ran this query and pasted the results here if anybody wants to save the time of running it themselves.
The query returns time zones grouped by offset so that it will be easier to chose:
SELECT utc_offset, is_dst,
ltrim(
trim(string_agg(distinct (CASE WHEN abbrev NOT LIKE '+%' AND abbrev NOT LIKE '-%' AND abbrev != name THEN abbrev ELSE '' END), ' ')) ||
' ' || string_agg(name, ', ' ORDER BY name)
)
FROM pg_timezone_names
WHERE name NOT LIKE 'posix/%'
AND name NOT LIKE 'Etc/%'
AND name NOT IN ('HST', 'Factory', 'GMT', 'GMT+0', 'GMT-0', 'GMT0', 'localtime', 'UCT', 'Universal', 'UTC', 'PST8PDT', 'ROK', 'W-SU', 'MST', 'CST6CDT')
GROUP BY utc_offset, is_dst
ORDER BY utc_offset, is_dst
And result is:
-11,false,"SST Pacific/Midway, Pacific/Niue, Pacific/Pago_Pago, Pacific/Samoa, US/Samoa"
-10,false,"HST Pacific/Honolulu, Pacific/Johnston, Pacific/Rarotonga, Pacific/Tahiti, US/Hawaii"
-9:30,false,Pacific/Marquesas
-9,false,Pacific/Gambier
-9,true,"HDT America/Adak, America/Atka, US/Aleutian"
-8,false,Pacific/Pitcairn
-8,true,"AKDT America/Anchorage, America/Juneau, America/Metlakatla, America/Nome, America/Sitka, America/Yakutat, US/Alaska"
-7,false,"MST America/Creston, America/Dawson, America/Dawson_Creek, America/Fort_Nelson, America/Hermosillo, America/Phoenix, America/Whitehorse, Canada/Yukon, US/Arizona"
-7,true,"PDT America/Ensenada, America/Los_Angeles, America/Santa_Isabel, America/Tijuana, America/Vancouver, Canada/Pacific, Mexico/BajaNorte, US/Pacific"
-6,false,"CST America/Belize, America/Costa_Rica, America/El_Salvador, America/Guatemala, America/Managua, America/Regina, America/Swift_Current, America/Tegucigalpa, Canada/Saskatchewan, Chile/EasterIsland, Pacific/Easter, Pacific/Galapagos"
-6,true,"MDT America/Boise, America/Cambridge_Bay, America/Chihuahua, America/Denver, America/Edmonton, America/Inuvik, America/Mazatlan, America/Ojinaga, America/Shiprock, America/Yellowknife, Canada/Mountain, Mexico/BajaSur, MST7MDT, Navajo, US/Mountain"
-5,false,"EST America/Atikokan, America/Bogota, America/Cancun, America/Cayman, America/Coral_Harbour, America/Eirunepe, America/Guayaquil, America/Jamaica, America/Lima, America/Panama, America/Porto_Acre, America/Rio_Branco, Brazil/Acre, EST, Jamaica"
-5,true,"CDT America/Bahia_Banderas, America/Chicago, America/Indiana/Knox, America/Indiana/Tell_City, America/Knox_IN, America/Matamoros, America/Menominee, America/Merida, America/Mexico_City, America/Monterrey, America/North_Dakota/Beulah, America/North_Dakota/Center, America/North_Dakota/New_Salem, America/Rainy_River, America/Rankin_Inlet, America/Resolute, America/Winnipeg, Canada/Central, Mexico/General, US/Central, US/Indiana-Starke"
-4,false,"AST America/Anguilla, America/Antigua, America/Aruba, America/Asuncion, America/Barbados, America/Blanc-Sablon, America/Boa_Vista, America/Campo_Grande, America/Caracas, America/Cuiaba, America/Curacao, America/Dominica, America/Grenada, America/Guadeloupe, America/Guyana, America/Kralendijk, America/La_Paz, America/Lower_Princes, America/Manaus, America/Marigot, America/Martinique, America/Montserrat, America/Port_of_Spain, America/Porto_Velho, America/Puerto_Rico, America/Santiago, America/Santo_Domingo, America/St_Barthelemy, America/St_Kitts, America/St_Lucia, America/St_Thomas, America/St_Vincent, America/Tortola, America/Virgin, Brazil/West, Chile/Continental"
-4,true,"CDT EDT America/Detroit, America/Fort_Wayne, America/Grand_Turk, America/Havana, America/Indiana/Indianapolis, America/Indiana/Marengo, America/Indiana/Petersburg, America/Indianapolis, America/Indiana/Vevay, America/Indiana/Vincennes, America/Indiana/Winamac, America/Iqaluit, America/Kentucky/Louisville, America/Kentucky/Monticello, America/Louisville, America/Montreal, America/Nassau, America/New_York, America/Nipigon, America/Pangnirtung, America/Port-au-Prince, America/Thunder_Bay, America/Toronto, Canada/Eastern, Cuba, EST5EDT, posixrules, US/Eastern, US/East-Indiana, US/Michigan"
-3,false,"America/Araguaina, America/Argentina/Buenos_Aires, America/Argentina/Catamarca, America/Argentina/ComodRivadavia, America/Argentina/Cordoba, America/Argentina/Jujuy, America/Argentina/La_Rioja, America/Argentina/Mendoza, America/Argentina/Rio_Gallegos, America/Argentina/Salta, America/Argentina/San_Juan, America/Argentina/San_Luis, America/Argentina/Tucuman, America/Argentina/Ushuaia, America/Bahia, America/Belem, America/Buenos_Aires, America/Catamarca, America/Cayenne, America/Cordoba, America/Fortaleza, America/Jujuy, America/Maceio, America/Mendoza, America/Montevideo, America/Paramaribo, America/Punta_Arenas, America/Recife, America/Rosario, America/Santarem, America/Sao_Paulo, Antarctica/Palmer, Antarctica/Rothera, Atlantic/Stanley, Brazil/East"
-3,true,"ADT America/Glace_Bay, America/Goose_Bay, America/Halifax, America/Moncton, America/Thule, Atlantic/Bermuda, Canada/Atlantic"
-2:30,true,"NDT America/St_Johns, Canada/Newfoundland"
-2,false,"America/Noronha, Atlantic/South_Georgia, Brazil/DeNoronha"
-2,true,"America/Godthab, America/Miquelon, America/Nuuk"
-1,false,Atlantic/Cape_Verde
+0,false,"GMT UTC Africa/Abidjan, Africa/Accra, Africa/Bamako, Africa/Banjul, Africa/Bissau, Africa/Conakry, Africa/Dakar, Africa/Freetown, Africa/Lome, Africa/Monrovia, Africa/Nouakchott, Africa/Ouagadougou, Africa/Sao_Tome, Africa/Timbuktu, America/Danmarkshavn, Atlantic/Reykjavik, Atlantic/St_Helena, Greenwich, Iceland, Zulu"
+0,true,"America/Scoresbysund, Atlantic/Azores"
+1,false,"CET IST WAT Africa/Algiers, Africa/Bangui, Africa/Brazzaville, Africa/Casablanca, Africa/Douala, Africa/El_Aaiun, Africa/Kinshasa, Africa/Lagos, Africa/Libreville, Africa/Luanda, Africa/Malabo, Africa/Ndjamena, Africa/Niamey, Africa/Porto-Novo, Africa/Tunis, Eire, Europe/Dublin"
+1,true,"BST WEST Atlantic/Canary, Atlantic/Faeroe, Atlantic/Faroe, Atlantic/Madeira, Europe/Belfast, Europe/Guernsey, Europe/Isle_of_Man, Europe/Jersey, Europe/Lisbon, Europe/London, GB, GB-Eire, Portugal, WET"
+2,false,"CAT EET SAST Africa/Blantyre, Africa/Bujumbura, Africa/Cairo, Africa/Gaborone, Africa/Harare, Africa/Johannesburg, Africa/Juba, Africa/Khartoum, Africa/Kigali, Africa/Lubumbashi, Africa/Lusaka, Africa/Maputo, Africa/Maseru, Africa/Mbabane, Africa/Tripoli, Africa/Windhoek, Egypt, Europe/Kaliningrad, Libya"
+2,true,"CEST MEST Africa/Ceuta, Antarctica/Troll, Arctic/Longyearbyen, Atlantic/Jan_Mayen, CET, Europe/Amsterdam, Europe/Andorra, Europe/Belgrade, Europe/Berlin, Europe/Bratislava, Europe/Brussels, Europe/Budapest, Europe/Busingen, Europe/Copenhagen, Europe/Gibraltar, Europe/Ljubljana, Europe/Luxembourg, Europe/Madrid, Europe/Malta, Europe/Monaco, Europe/Oslo, Europe/Paris, Europe/Podgorica, Europe/Prague, Europe/Rome, Europe/San_Marino, Europe/Sarajevo, Europe/Skopje, Europe/Stockholm, Europe/Tirane, Europe/Vaduz, Europe/Vatican, Europe/Vienna, Europe/Warsaw, Europe/Zagreb, Europe/Zurich, MET, Poland"
+3,false,"EAT MSK Africa/Addis_Ababa, Africa/Asmara, Africa/Asmera, Africa/Dar_es_Salaam, Africa/Djibouti, Africa/Kampala, Africa/Mogadishu, Africa/Nairobi, Antarctica/Syowa, Asia/Aden, Asia/Baghdad, Asia/Bahrain, Asia/Istanbul, Asia/Kuwait, Asia/Qatar, Asia/Riyadh, Europe/Istanbul, Europe/Kirov, Europe/Minsk, Europe/Moscow, Europe/Simferopol, Europe/Volgograd, Indian/Antananarivo, Indian/Comoro, Indian/Mayotte, Turkey"
+3,true,"EEST IDT Asia/Amman, Asia/Beirut, Asia/Damascus, Asia/Famagusta, Asia/Gaza, Asia/Hebron, Asia/Jerusalem, Asia/Nicosia, Asia/Tel_Aviv, EET, Europe/Athens, Europe/Bucharest, Europe/Chisinau, Europe/Helsinki, Europe/Kiev, Europe/Mariehamn, Europe/Nicosia, Europe/Riga, Europe/Sofia, Europe/Tallinn, Europe/Tiraspol, Europe/Uzhgorod, Europe/Vilnius, Europe/Zaporozhye, Israel"
+4,false,"Asia/Baku, Asia/Dubai, Asia/Muscat, Asia/Tbilisi, Asia/Yerevan, Europe/Astrakhan, Europe/Samara, Europe/Saratov, Europe/Ulyanovsk, Indian/Mahe, Indian/Mauritius, Indian/Reunion"
+4:30,false,Asia/Kabul
+4:30,true,"Asia/Tehran, Iran"
+5,false,"PKT Antarctica/Mawson, Asia/Aqtau, Asia/Aqtobe, Asia/Ashgabat, Asia/Ashkhabad, Asia/Atyrau, Asia/Dushanbe, Asia/Karachi, Asia/Oral, Asia/Qyzylorda, Asia/Samarkand, Asia/Tashkent, Asia/Yekaterinburg, Indian/Kerguelen, Indian/Maldives"
+5:30,false,"IST Asia/Calcutta, Asia/Colombo, Asia/Kolkata"
+5:45,false,"Asia/Kathmandu, Asia/Katmandu"
+6,false,"Antarctica/Vostok, Asia/Almaty, Asia/Bishkek, Asia/Dacca, Asia/Dhaka, Asia/Kashgar, Asia/Omsk, Asia/Qostanay, Asia/Thimbu, Asia/Thimphu, Asia/Urumqi, Indian/Chagos"
+6:30,false,"Asia/Rangoon, Asia/Yangon, Indian/Cocos"
+7,false,"WIB Antarctica/Davis, Asia/Bangkok, Asia/Barnaul, Asia/Ho_Chi_Minh, Asia/Hovd, Asia/Jakarta, Asia/Krasnoyarsk, Asia/Novokuznetsk, Asia/Novosibirsk, Asia/Phnom_Penh, Asia/Pontianak, Asia/Saigon, Asia/Tomsk, Asia/Vientiane, Indian/Christmas"
+8,false,"AWST CST HKT PST WITA Asia/Brunei, Asia/Choibalsan, Asia/Chongqing, Asia/Chungking, Asia/Harbin, Asia/Hong_Kong, Asia/Irkutsk, Asia/Kuala_Lumpur, Asia/Kuching, Asia/Macao, Asia/Macau, Asia/Makassar, Asia/Manila, Asia/Shanghai, Asia/Singapore, Asia/Taipei, Asia/Ujung_Pandang, Asia/Ulaanbaatar, Asia/Ulan_Bator, Australia/Perth, Australia/West, Hongkong, PRC, ROC, Singapore"
+8:45,false,Australia/Eucla
+9,false,"JST KST WIT Asia/Chita, Asia/Dili, Asia/Jayapura, Asia/Khandyga, Asia/Pyongyang, Asia/Seoul, Asia/Tokyo, Asia/Yakutsk, Japan, Pacific/Palau"
+9:30,false,"ACST Australia/Adelaide, Australia/Broken_Hill, Australia/Darwin, Australia/North, Australia/South, Australia/Yancowinna"
+10,false,"AEST ChST Antarctica/DumontDUrville, Antarctica/Macquarie, Asia/Ust-Nera, Asia/Vladivostok, Australia/ACT, Australia/Brisbane, Australia/Canberra, Australia/Currie, Australia/Hobart, Australia/Lindeman, Australia/Melbourne, Australia/NSW, Australia/Queensland, Australia/Sydney, Australia/Tasmania, Australia/Victoria, Pacific/Chuuk, Pacific/Guam, Pacific/Port_Moresby, Pacific/Saipan, Pacific/Truk, Pacific/Yap"
+10:30,false,"Australia/LHI, Australia/Lord_Howe"
+11,false,"Antarctica/Casey, Asia/Magadan, Asia/Sakhalin, Asia/Srednekolymsk, Pacific/Bougainville, Pacific/Efate, Pacific/Guadalcanal, Pacific/Kosrae, Pacific/Norfolk, Pacific/Noumea, Pacific/Pohnpei, Pacific/Ponape"
+12,false,"NZST Antarctica/McMurdo, Antarctica/South_Pole, Asia/Anadyr, Asia/Kamchatka, Kwajalein, NZ, Pacific/Auckland, Pacific/Fiji, Pacific/Funafuti, Pacific/Kwajalein, Pacific/Majuro, Pacific/Nauru, Pacific/Tarawa, Pacific/Wake, Pacific/Wallis"
+12:45,false,"NZ-CHAT, Pacific/Chatham"
+13,false,"Pacific/Apia, Pacific/Enderbury, Pacific/Fakaofo, Pacific/Kanton, Pacific/Tongatapu"
+14,false,Pacific/Kiritimati
This is ready to use for a Time Zone selector. The DST i.e. a summer time items I show in a different color.

Ruby date format for PayPal Button Manager API

I can't get a date format that PayPal will accept via its PayPal Button manager API. "The start date specified is invalid." is the error.
Attempt 1: copy the string directly from the documentation:
"start_date": "2017-12-22T09:13:49Z"
I saw this https://github.com/paypal/PayPal-Ruby-SDK/issues/107 so tried
strftime('%Y-%m-%dT%H:%M:%SZ') and utc.iso8601
start_date = "1980-02-19T00:37:04Z"
start_date = (DateTime.now - 10.years).utc.iso8601
start_date = (DateTime.now - 10.years).utc
#bm_build_button_search = #api.build_bm_button_search({ "start_date" => start_date })
# Make API call & get response
#bm_button_search_response = #api.BMButtonSearch(#bm_build_button_search)
#Errors=[#<PayPal::SDK::ButtonManager::DataTypes::ErrorType:0x007fa58b12e110 #ShortMessage="Invalid Argument", #LongMessage="The start date specified is invalid.", #ErrorCode="11998
(byebug) #bm_build_button_search.start_date.class
PayPal::SDK::Core::API::DataTypes::SimpleTypes::DateTime
So it looks like PayPal is fine with this DateTime format but when I call
#api.BMButtonSearch(#bm_build_button_search)
I get the error #LongMessage="The start date specified is invalid."
I just verified following script using Ruby version 2.3.3 and its working fine. Following is the script i used in ruby console.
Step1: install Paypal SDK
$ gem install paypal-sdk-buttonmanager
Step2:
require 'paypal-sdk-buttonmanager'
#api = PayPal::SDK::ButtonManager::API.new(
:mode => "sandbox", # Set "live" for production
:app_id => "APP-80W284485P519543T",
:username => "jb-us-seller_api1.paypal.com",
:password => "WX4WTU3S8MY44S7F",
:signature => "AFcWxV21C7fd0v3bYYYRCpSSRl31A7yDhhsPUU2XhtMoZXsWHFxu-
RWy" )
Step3:
start_date = "1980-02-19T00:37:04Z"
#bm_build_button_search = #api.build_bm_button_search({ "start_date" => start_date })
#bm_button_search_response = #api.BMButtonSearch(#bm_build_button_search)
Response: I, [2017-05-06T05:43:14.803444 #6541] INFO -- : Action: BMButtonSearch
I, [2017-05-06T05:43:14.803551 #6541] INFO -- : Request[post]: https://api-3t.sandbox.paypal.com/2.0/
I, [2017-05-06T05:43:27.057413 #6541] INFO -- : Response[200]: OK, Duration: 12.254s
**Please verify using Ruby 2.3.3. Screenshot has been attached. thanks!**
reference: https://github.com/paypal/buttonmanager-sdk-ruby

is there any way to get key "last-modified" from zend Google Doc Adapter?

I write some code like this to getting cell value in google Spreadsheet
this code exactly work
$query = new Zend_Gdata_Spreadsheets_DocumentQuery();
$query->setSpreadsheetKey($this->spreadsheetId);
$feed = $this->spreadsheetService->getWorksheetFeed($query);
var_dump($feed);
but I need value of last modified this spreadsheet
this value are protected in $feed object :
["Last-modified"]=>
string(29) "Wed, 18 Sep 2013 08:58:44 GMT"
is there any way to get key "last-modified" of Goolgle Doc?
AND How i can access it via zend V.1?

Current date / time to RFC 2822 date function with vb / classic asp

I am trying to write a script to push data out to an amazon s3 bucket and I need to generate what I believe is an RFC 2822 date to send in the header request.
The date looks like this "Tue, 12 June 2012 23:41:58 +0000"
I just need a function to generate the correct time format as I am getting the following error.
RequestTimeTooSkewed The difference between the request time and the current time is too large.
This is what I have so far...
<%
sTimeStamp = "Tue, 12 June 2012 23:41:58 +00002012-06-12T22:45:47Z"
sAWSAccessKeyId = "AESDQWDQWD"
sSignature=Encrypt("SecretQWEQWEQWEQWEYAYAY")
AWSServiceUrl = "https://s3.amazonaws.com/"
Set oXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
oXMLHTTP.open "GET", AWSServiceUrl, False
oXMLHTTP.setRequestHeader "Authorization", "AWS " & sAWSAccessKeyId & ":" & sSignature
oXMLHTTP.setRequestHeader "x-amz-date", sTimeStamp
on error resume next
oXMLHTTP.send sRequest
Response.Write oXMLHTTP.responseText
%>
Any ideas?
The simplest way to do it is to get JScript to help:
<script runat="server" language="javascript">
function JSNow() { return new Date(); }
</script>
Now you can get the string format for the time required with:
Dim sTimeStamp: sTimeStamp = JSNow().toString()