Time Utilities API Examples
Complete code examples and integration guides for the Time Utilities API in multiple programming languages.Quick Examples
Get Current Time
Copy
curl "https://api.sinaty.business/time/?operation=now"
Convert Timezone
Copy
curl "https://api.sinaty.business/time/?operation=convert&time=2024-01-01T12:00:00&from=UTC&to=America/New_York"
Calculate Time Difference
Copy
curl "https://api.sinaty.business/time/?operation=difference&time1=2024-01-01T12:00:00&time2=2024-01-02T12:00:00"
JavaScript/Node.js Examples
Get Current Time
Copy
async function getCurrentTime(timezone = 'UTC') {
try {
const response = await fetch(
`https://api.sinaty.business/time/?operation=now&timezone=${timezone}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.time;
} catch (error) {
console.error('Error getting current time:', error);
return null;
}
}
// Usage
const currentTime = await getCurrentTime('UTC');
const localTime = await getCurrentTime('America/New_York');
console.log('Current UTC time:', currentTime);
console.log('Current NY time:', localTime);
Timezone Conversion
Copy
async function convertTimezone(time, fromTimezone = 'UTC', toTimezone) {
try {
const params = new URLSearchParams({
operation: 'convert',
time: time,
from: fromTimezone,
to: toTimezone
});
const response = await fetch(
`https://api.sinaty.business/time/?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.converted_time;
} catch (error) {
console.error('Error converting timezone:', error);
return null;
}
}
// Usage
const convertedTime = await convertTimezone(
'2024-01-01T12:00:00',
'UTC',
'America/New_York'
);
console.log('Converted time:', convertedTime);
Time Difference Calculation
Copy
async function calculateTimeDifference(time1, time2, unit = 'seconds') {
try {
const params = new URLSearchParams({
operation: 'difference',
time1: time1,
time2: time2,
unit: unit
});
const response = await fetch(
`https://api.sinaty.business/time/?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.difference;
} catch (error) {
console.error('Error calculating time difference:', error);
return null;
}
}
// Usage
const difference = await calculateTimeDifference(
'2024-01-01T12:00:00',
'2024-01-02T12:00:00',
'hours'
);
console.log('Time difference in hours:', difference);
Add/Subtract Time
Copy
async function addTime(time, amount, unit = 'hours') {
try {
const params = new URLSearchParams({
operation: 'add',
time: time,
amount: amount.toString(),
unit: unit
});
const response = await fetch(
`https://api.sinaty.business/time/?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.result;
} catch (error) {
console.error('Error adding time:', error);
return null;
}
}
// Usage
const futureTime = await addTime('2024-01-01T12:00:00', 24, 'hours');
const pastTime = await addTime('2024-01-01T12:00:00', -2, 'days');
console.log('Future time:', futureTime);
console.log('Past time:', pastTime);
Format Time
Copy
async function formatTime(time, format = 'ISO') {
try {
const params = new URLSearchParams({
operation: 'format',
time: time,
format: format
});
const response = await fetch(
`https://api.sinaty.business/time/?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.formatted_time;
} catch (error) {
console.error('Error formatting time:', error);
return null;
}
}
// Usage
const formattedTime = await formatTime('2024-01-01T12:00:00', 'YYYY-MM-DD HH:mm:ss');
console.log('Formatted time:', formattedTime);
Python Examples
Get Current Time
Copy
import requests
import json
def get_current_time(timezone='UTC'):
"""Get current time in specified timezone."""
try:
url = "https://api.sinaty.business/time/"
params = {
'operation': 'now',
'timezone': timezone
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['time']
except requests.exceptions.RequestException as e:
print(f"Error getting current time: {e}")
return None
# Usage
current_time = get_current_time('UTC')
local_time = get_current_time('America/New_York')
print(f"Current UTC time: {current_time}")
print(f"Current NY time: {local_time}")
Timezone Conversion
Copy
def convert_timezone(time, from_timezone='UTC', to_timezone=None):
"""Convert time between timezones."""
try:
url = "https://api.sinaty.business/time/"
params = {
'operation': 'convert',
'time': time,
'from': from_timezone,
'to': to_timezone
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['converted_time']
except requests.exceptions.RequestException as e:
print(f"Error converting timezone: {e}")
return None
# Usage
converted_time = convert_timezone(
'2024-01-01T12:00:00',
'UTC',
'America/New_York'
)
print(f"Converted time: {converted_time}")
Time Difference Calculation
Copy
def calculate_time_difference(time1, time2, unit='seconds'):
"""Calculate difference between two times."""
try:
url = "https://api.sinaty.business/time/"
params = {
'operation': 'difference',
'time1': time1,
'time2': time2,
'unit': unit
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['difference']
except requests.exceptions.RequestException as e:
print(f"Error calculating time difference: {e}")
return None
# Usage
difference = calculate_time_difference(
'2024-01-01T12:00:00',
'2024-01-02T12:00:00',
'hours'
)
print(f"Time difference in hours: {difference}")
Add/Subtract Time
Copy
def add_time(time, amount, unit='hours'):
"""Add or subtract time from a given time."""
try:
url = "https://api.sinaty.business/time/"
params = {
'operation': 'add',
'time': time,
'amount': str(amount),
'unit': unit
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['result']
except requests.exceptions.RequestException as e:
print(f"Error adding time: {e}")
return None
# Usage
future_time = add_time('2024-01-01T12:00:00', 24, 'hours')
past_time = add_time('2024-01-01T12:00:00', -2, 'days')
print(f"Future time: {future_time}")
print(f"Past time: {past_time}")
Format Time
Copy
def format_time(time, format_str='ISO'):
"""Format time in specified format."""
try:
url = "https://api.sinaty.business/time/"
params = {
'operation': 'format',
'time': time,
'format': format_str
}
response = requests.get(url, params=params)
response.raise_for_status()
data = response.json()
return data['formatted_time']
except requests.exceptions.RequestException as e:
print(f"Error formatting time: {e}")
return None
# Usage
formatted_time = format_time('2024-01-01T12:00:00', 'YYYY-MM-DD HH:mm:ss')
print(f"Formatted time: {formatted_time}")
PHP Examples
Get Current Time
Copy
<?php
function getCurrentTime($timezone = 'UTC') {
$url = "https://api.sinaty.business/time/";
$params = http_build_query([
'operation' => 'now',
'timezone' => $timezone
]);
$fullUrl = $url . '?' . $params;
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Content-Type: application/json'
]
]);
$response = file_get_contents($fullUrl, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
return $data['time'] ?? null;
}
// Usage
$currentTime = getCurrentTime('UTC');
$localTime = getCurrentTime('America/New_York');
echo "Current UTC time: " . $currentTime . "\n";
echo "Current NY time: " . $localTime . "\n";
?>
Timezone Conversion
Copy
<?php
function convertTimezone($time, $fromTimezone = 'UTC', $toTimezone) {
$url = "https://api.sinaty.business/time/";
$params = http_build_query([
'operation' => 'convert',
'time' => $time,
'from' => $fromTimezone,
'to' => $toTimezone
]);
$fullUrl = $url . '?' . $params;
$context = stream_context_create([
'http' => [
'method' => 'GET',
'header' => 'Content-Type: application/json'
]
]);
$response = file_get_contents($fullUrl, false, $context);
if ($response === false) {
return null;
}
$data = json_decode($response, true);
return $data['converted_time'] ?? null;
}
// Usage
$convertedTime = convertTimezone('2024-01-01T12:00:00', 'UTC', 'America/New_York');
echo "Converted time: " . $convertedTime . "\n";
?>
Go Examples
Get Current Time
Copy
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
type TimeResponse struct {
Time string `json:"time"`
}
func getCurrentTime(timezone string) (string, error) {
baseURL := "https://api.sinaty.business/time/"
params := url.Values{}
params.Add("operation", "now")
params.Add("timezone", timezone)
fullURL := baseURL + "?" + params.Encode()
resp, err := http.Get(fullURL)
if err != nil {
return "", err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
var response TimeResponse
err = json.Unmarshal(body, &response)
if err != nil {
return "", err
}
return response.Time, nil
}
func main() {
currentTime, err := getCurrentTime("UTC")
if err != nil {
fmt.Printf("Error: %v\n", err)
return
}
fmt.Printf("Current UTC time: %s\n", currentTime)
}
Ruby Examples
Get Current Time
Copy
require 'net/http'
require 'json'
require 'uri'
def get_current_time(timezone = 'UTC')
url = "https://api.sinaty.business/time/"
uri = URI(url)
params = {
'operation' => 'now',
'timezone' => timezone
}
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)
if response.is_a?(Net::HTTPSuccess)
data = JSON.parse(response.body)
return data['time']
else
puts "Error: #{response.code} - #{response.message}"
return nil
end
rescue => e
puts "Error getting current time: #{e.message}"
return nil
end
# Usage
current_time = get_current_time('UTC')
puts "Current UTC time: #{current_time}"
cURL Examples
Basic Time Operations
Copy
# Get current time
curl "https://api.sinaty.business/time/?operation=now"
# Get current time in specific timezone
curl "https://api.sinaty.business/time/?operation=now&timezone=America/New_York"
# Convert timezone
curl "https://api.sinaty.business/time/?operation=convert&time=2024-01-01T12:00:00&from=UTC&to=America/New_York"
# Calculate time difference
curl "https://api.sinaty.business/time/?operation=difference&time1=2024-01-01T12:00:00&time2=2024-01-02T12:00:00&unit=hours"
Advanced Time Operations
Copy
# Add time
curl "https://api.sinaty.business/time/?operation=add&time=2024-01-01T12:00:00&amount=24&unit=hours"
# Subtract time
curl "https://api.sinaty.business/time/?operation=add&time=2024-01-01T12:00:00&amount=-2&unit=days"
# Format time
curl "https://api.sinaty.business/time/?operation=format&time=2024-01-01T12:00:00&format=YYYY-MM-DD HH:mm:ss"
# Get time components
curl "https://api.sinaty.business/time/?operation=components&time=2024-01-01T12:30:45"
Integration Examples
React Component for Time Display
Copy
import React, { useState, useEffect } from 'react';
function TimeDisplay() {
const [currentTime, setCurrentTime] = useState(null);
const [timezone, setTimezone] = useState('UTC');
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const fetchCurrentTime = async (tz) => {
setLoading(true);
setError(null);
try {
const response = await fetch(
`https://api.sinaty.business/time/?operation=now&timezone=${tz}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
setCurrentTime(data.time);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchCurrentTime(timezone);
const interval = setInterval(() => fetchCurrentTime(timezone), 1000);
return () => clearInterval(interval);
}, [timezone]);
return (
<div>
<h2>Current Time</h2>
<select
value={timezone}
onChange={(e) => setTimezone(e.target.value)}
>
<option value="UTC">UTC</option>
<option value="America/New_York">New York</option>
<option value="Europe/London">London</option>
<option value="Asia/Tokyo">Tokyo</option>
</select>
{loading && <p>Loading...</p>}
{currentTime && <p>Current time: {currentTime}</p>}
{error && <p style={{color: 'red'}}>Error: {error}</p>}
</div>
);
}
export default TimeDisplay;
Express.js Time Processing Middleware
Copy
const express = require('express');
const fetch = require('node-fetch');
const app = express();
app.use(express.json());
// Middleware to process time operations
async function processTime(req, res, next) {
try {
const { operation, time, timezone, from, to, amount, unit } = req.body;
if (!operation) {
return res.status(400).json({ error: 'Operation is required' });
}
const params = new URLSearchParams({
operation: operation
});
if (time) params.append('time', time);
if (timezone) params.append('timezone', timezone);
if (from) params.append('from', from);
if (to) params.append('to', to);
if (amount) params.append('amount', amount);
if (unit) params.append('unit', unit);
const response = await fetch(
`https://api.sinaty.business/time/?${params}`
);
if (!response.ok) {
throw new Error(`API error: ${response.status}`);
}
const data = await response.json();
req.timeResult = data;
next();
} catch (error) {
res.status(500).json({ error: error.message });
}
}
// Route for time processing
app.post('/process-time', processTime, (req, res) => {
res.json(req.timeResult);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
Time Utility Service
Copy
class TimeUtilityService {
async getCurrentTime(timezone = 'UTC') {
try {
const response = await fetch(
`https://api.sinaty.business/time/?operation=now&timezone=${timezone}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.time;
} catch (error) {
console.error('Error getting current time:', error);
return null;
}
}
async convertTimezone(time, fromTimezone, toTimezone) {
try {
const params = new URLSearchParams({
operation: 'convert',
time: time,
from: fromTimezone,
to: toTimezone
});
const response = await fetch(
`https://api.sinaty.business/time/?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.converted_time;
} catch (error) {
console.error('Error converting timezone:', error);
return null;
}
}
async calculateTimeDifference(time1, time2, unit = 'seconds') {
try {
const params = new URLSearchParams({
operation: 'difference',
time1: time1,
time2: time2,
unit: unit
});
const response = await fetch(
`https://api.sinaty.business/time/?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.difference;
} catch (error) {
console.error('Error calculating time difference:', error);
return null;
}
}
async addTime(time, amount, unit = 'hours') {
try {
const params = new URLSearchParams({
operation: 'add',
time: time,
amount: amount.toString(),
unit: unit
});
const response = await fetch(
`https://api.sinaty.business/time/?${params}`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data.result;
} catch (error) {
console.error('Error adding time:', error);
return null;
}
}
}
// Usage
const timeService = new TimeUtilityService();
// Get current time in different timezones
const utcTime = await timeService.getCurrentTime('UTC');
const nyTime = await timeService.getCurrentTime('America/New_York');
// Convert timezone
const convertedTime = await timeService.convertTimezone(
'2024-01-01T12:00:00',
'UTC',
'America/New_York'
);
// Calculate time difference
const difference = await timeService.calculateTimeDifference(
'2024-01-01T12:00:00',
'2024-01-02T12:00:00',
'hours'
);
console.log('UTC time:', utcTime);
console.log('NY time:', nyTime);
console.log('Converted time:', convertedTime);
console.log('Time difference:', difference);
Common Use Cases
Scheduling Applications
Copy
async function scheduleEvent(startTime, duration, timezone) {
const endTime = await addTime(startTime, duration, 'minutes');
const localStartTime = await convertTimezone(startTime, 'UTC', timezone);
const localEndTime = await convertTimezone(endTime, 'UTC', timezone);
return {
startTime: localStartTime,
endTime: localEndTime,
duration: duration
};
}
// Usage
const event = await scheduleEvent('2024-01-01T14:00:00Z', 60, 'America/New_York');
console.log('Scheduled event:', event);
Time Tracking
Copy
async function calculateWorkHours(startTime, endTime) {
const difference = await calculateTimeDifference(startTime, endTime, 'hours');
return {
hours: difference,
minutes: await calculateTimeDifference(startTime, endTime, 'minutes'),
seconds: await calculateTimeDifference(startTime, endTime, 'seconds')
};
}
// Usage
const workHours = await calculateWorkHours(
'2024-01-01T09:00:00',
'2024-01-01T17:30:00'
);
console.log('Work hours:', workHours);
Countdown Timer
Copy
async function createCountdown(targetTime, timezone = 'UTC') {
const currentTime = await getCurrentTime(timezone);
const remaining = await calculateTimeDifference(currentTime, targetTime, 'seconds');
return {
targetTime: targetTime,
currentTime: currentTime,
remainingSeconds: Math.max(0, remaining),
isExpired: remaining <= 0
};
}
// Usage
const countdown = await createCountdown('2024-12-31T23:59:59', 'America/New_York');
console.log('Countdown:', countdown);