Code Examples: AD to BS & BS to AD Date Conversion
Ready-to-use code snippets for converting Gregorian (AD) to Bikram Sambat (BS) dates and vice versa. Perfect for AI coders, developers, and anyone looking to integrate Nepali date conversion into their applications.
API Base URL
https://sudhanparajuli.com.np/api/
- AD to BS:
/api/ad-to-bs/YYYY/MM/DD
- BS to AD:
/api/bs-to-ad/YYYY/MM/DD
- Format: JSON response with success status and converted date
- CORS: Enabled for all origins
JavaScript Examples
Convert AD to BS (Gregorian to Bikram Sambat)
// Convert AD date to BS date using fetch API
async function convertADToBS(year, month, day) {
try {
const response = await fetch(`https://sudhanparajuli.com.np/api/ad-to-bs/${year}/${month}/${day}`);
const data = await response.json();
if (data.success) {
console.log(`AD ${year}-${month}-${day} = BS ${data.result.year}-${data.result.month}-${data.result.day}`);
return data.result;
} else {
throw new Error(data.error || 'Conversion failed');
}
} catch (error) {
console.error('Error converting AD to BS:', error);
return null;
}
}
// Example usage
convertADToBS(2024, 1, 15).then(result => {
if (result) {
document.getElementById('bs-date').textContent =
`${result.year}/${result.month}/${result.day}`;
}
});
// jQuery version
$.get('https://sudhanparajuli.com.np/api/ad-to-bs/2024/1/15')
.done(function(data) {
if (data.success) {
$('#result').text(data.result.year + '/' + data.result.month + '/' + data.result.day);
}
})
.fail(function() {
console.log('API request failed');
});
Convert BS to AD (Bikram Sambat to Gregorian)
// Convert BS date to AD date
async function convertBSToAD(year, month, day) {
try {
const response = await fetch(`https://sudhanparajuli.com.np/api/bs-to-ad/${year}/${month}/${day}`);
const data = await response.json();
if (data.success) {
console.log(`BS ${year}-${month}-${day} = AD ${data.result.year}-${data.result.month}-${data.result.day}`);
return data.result;
} else {
throw new Error(data.error || 'Conversion failed');
}
} catch (error) {
console.error('Error converting BS to AD:', error);
return null;
}
}
// Example: Convert today's BS date to AD
convertBSToAD(2081, 1, 15).then(result => {
if (result) {
console.log('Converted AD date:', result);
// Use result.year, result.month, result.day
}
});
Python Examples
Using requests library
import requests
import json
def convert_ad_to_bs(year, month, day):
"""Convert Gregorian (AD) date to Bikram Sambat (BS) date"""
url = f"https://sudhanparajuli.com.np/api/ad-to-bs/{year}/{month}/{day}"
try:
response = requests.get(url)
response.raise_for_status() # Raise exception for bad status codes
data = response.json()
if data.get('success'):
bs_date = data['result']
print(f"AD {year}-{month}-{day} = BS {bs_date['year']}-{bs_date['month']}-{bs_date['day']}")
return bs_date
else:
print(f"Error: {data.get('error', 'Unknown error')}")
return None
except requests.RequestException as e:
print(f"Request failed: {e}")
return None
def convert_bs_to_ad(year, month, day):
"""Convert Bikram Sambat (BS) date to Gregorian (AD) date"""
url = f"https://sudhanparajuli.com.np/api/bs-to-ad/{year}/{month}/{day}"
try:
response = requests.get(url)
response.raise_for_status()
data = response.json()
if data.get('success'):
ad_date = data['result']
print(f"BS {year}-{month}-{day} = AD {ad_date['year']}-{ad_date['month']}-{ad_date['day']}")
return ad_date
else:
print(f"Error: {data.get('error', 'Unknown error')}")
return None
except requests.RequestException as e:
print(f"Request failed: {e}")
return None
# Example usage
if __name__ == "__main__":
# Convert AD to BS
bs_result = convert_ad_to_bs(2024, 10, 15)
# Convert BS to AD
ad_result = convert_bs_to_ad(2081, 6, 29)
# Batch conversion
ad_dates = [(2024, 1, 1), (2024, 12, 31), (2023, 4, 13)]
for year, month, day in ad_dates:
convert_ad_to_bs(year, month, day)
Using urllib (no external dependencies)
import urllib.request
import json
def convert_date_api(year, month, day, conversion_type='ad-to-bs'):
"""Convert date using the API without external dependencies"""
url = f"https://sudhanparajuli.com.np/api/{conversion_type}/{year}/{month}/{day}"
try:
with urllib.request.urlopen(url) as response:
data = json.loads(response.read().decode())
if data.get('success'):
return data['result']
else:
print(f"API Error: {data.get('error', 'Unknown error')}")
return None
except Exception as e:
print(f"Error: {e}")
return None
# Example usage
ad_to_bs = convert_date_api(2024, 10, 15, 'ad-to-bs')
bs_to_ad = convert_date_api(2081, 6, 29, 'bs-to-ad')
PHP Examples
<?php
/**
* Convert AD date to BS date using the API
*/
function convertADToBS($year, $month, $day) {
$url = "https://sudhanparajuli.com.np/api/ad-to-bs/{$year}/{$month}/{$day}";
$response = file_get_contents($url);
if ($response === FALSE) {
return null;
}
$data = json_decode($response, true);
if (isset($data['success']) && $data['success']) {
return $data['result'];
}
return null;
}
/**
* Convert BS date to AD date using the API
*/
function convertBSToAD($year, $month, $day) {
$url = "https://sudhanparajuli.com.np/api/bs-to-ad/{$year}/{$month}/{$day}";
$response = file_get_contents($url);
if ($response === FALSE) {
return null;
}
$data = json_decode($response, true);
if (isset($data['success']) && $data['success']) {
return $data['result'];
}
return null;
}
// Example usage
$bs_date = convertADToBS(2024, 10, 15);
if ($bs_date) {
echo "AD 2024-10-15 = BS {$bs_date['year']}-{$bs_date['month']}-{$bs_date['day']}\n";
}
$ad_date = convertBSToAD(2081, 6, 29);
if ($ad_date) {
echo "BS 2081-6-29 = AD {$ad_date['year']}-{$ad_date['month']}-{$ad_date['day']}\n";
}
// Using cURL for better error handling
function convertDateWithCurl($year, $month, $day, $type = 'ad-to-bs') {
$url = "https://sudhanparajuli.com.np/api/{$type}/{$year}/{$month}/{$day}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode === 200 && $response !== false) {
$data = json_decode($response, true);
return isset($data['success']) && $data['success'] ? $data['result'] : null;
}
return null;
}
?>
Iframe Widget Embed Code
Embed the date converter directly into your website, blog, or application:
Basic Iframe Embed
<!-- Basic iframe embed for AD to BS and BS to AD converter -->
<iframe
src="https://sudhanparajuli.com.np/iframe"
width="100%"
height="400"
frameborder="0"
title="Nepali Date Converter - AD to BS and BS to AD"
style="border: 1px solid #ddd; border-radius: 8px;">
</iframe>
Responsive Iframe with CSS
<!-- Responsive iframe wrapper -->
<div style="position: relative; width: 100%; height: 0; padding-bottom: 56.25%;">
<iframe
src="https://sudhanparajuli.com.np/iframe"
style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; border: none; border-radius: 8px;"
title="BS to AD Date Converter Widget"
loading="lazy">
</iframe>
</div>
WordPress Shortcode Style
<!-- For WordPress or similar CMS -->
<div class="nepali-date-converter-widget">
<iframe
src="https://sudhanparajuli.com.np/iframe"
width="100%"
height="450"
frameborder="0"
scrolling="no"
title="Nepali Date Converter Widget - Convert AD to BS and BS to AD"
allow="clipboard-write">
<p>Your browser doesn't support iframes. <a href="https://sudhanparajuli.com.np/convert" target="_blank">Open Date Converter</a></p>
</iframe>
</div>
API Response Examples
Successful AD to BS Conversion
{
"success": true,
"input": {
"year": 2024,
"month": 10,
"day": 15,
"type": "AD"
},
"result": {
"year": 2081,
"month": 6,
"day": 29,
"type": "BS"
}
}
Successful BS to AD Conversion
{
"success": true,
"input": {
"year": 2081,
"month": 6,
"day": 29,
"type": "BS"
},
"result": {
"year": 2024,
"month": 10,
"day": 15,
"type": "AD"
}
}
Error Response
{
"error": "Invalid date: month must be between 1 and 12"
}
Common Use Cases & Tips
For AI Coders & ChatGPT
- Copy-paste ready code examples above
- All examples include error handling
- No authentication required
- CORS enabled for browser usage
- Supports all modern programming languages
Integration Tips
- Cache results to reduce API calls
- Validate input dates before API calls
- Handle network timeouts gracefully
- Use HTTPS for secure connections
- Rate limiting: Be respectful with requests
Quick Start for Developers
1. Choose your programming language from the examples above
2. Copy the relevant code snippet
3. Replace the date values with your data
4. Run the code - it works immediately!
5. For websites: Use the iframe embed code