datetime convert to date string - javascript - javascript

I have following datetime value in a json :
Fri Jan 22 2016 14:34:38 GMT-0500
I would like to display something like "January 22, 2016"
How could I achieve this in javascript. I have JQuery, Extjs libraries available.

Try creating object having properties of abbreviated months, values of full month, using for..in loop , String.prototype.slice(), String.prototype.replace()
var months = {
"Jan":"January",
"Feb":"February",
"Mar":"March",
"Apr":"April",
"May":"May",
"Jun":"June",
"Jul":"July",
"Aug":"August",
"Sep":"September",
"Oct":"October",
"Nov":"November",
"Dec":"December"
};
var date = "Fri Jan 22 2016 14:34:38 GMT-0500";
// extract "Jan 22 2016" from `date`
var d = date.slice(4, -18);
for (var prop in months) {
if (new RegExp(prop).test(d)) {
// replace abbreviated month with full month name
d = d.replace(prop, months[prop]);
// replace day with day followed by comma `,` character
d = d.replace(/(\d{2})(?=\s)/, "$1,")
}
}
document.body.textContent = d

This question is addressed to the same question of yours. You can use the functions shown here to construct the date string as you want.
// This could be any Date String
var str = "Fri Feb 08 2013 09:47:57 GMT +0530 (IST)";
var date = new Date(str);
This will then give you access to all the Date functions (MDN)
For example:
var day = date.getDate(); //Date of the month: 2 in our example
var month = date.getMonth(); //Month of the Year: 0-based index, so 1 in our example
var year = date.getFullYear() //Year: 2013
Extract date and time from string using Javascript

Found this crazy method here, but worked!
Converting milliseconds to a date (jQuery/JS)
Here is the fiddle that i'v done
https://jsfiddle.net/Ripper1992/hj6L2Lvz/
var now = new Date("Fri Jan 22 2016 14:34:38 GMT-0500");
alert(now.customFormat( "#MMMM# #DD#, #YYYY#" ) );
customFormat is the function called to get each part of the Data, parse and replace based on the #MMMM# or #DD# or #SS# defined by the user.
And here is the complete function with the documentation
http://phrogz.net/JS/FormatDateTime_JS.txt

Related

Javascript - Determine date format based on timezone

I have two date strings and a timezone (which will vary for each user). With this information I need to construct two date objects.
//information I have
var date1 = '05/05/2018'
var date2 = '06/05/2018'
var timezone = 'Australia/Sydney'
//date objects
var date1 = new Date(date1); // Sat May 05 00:00:00 GMT+00:00 2018
var date2 = new Date(date2); // Tue Jun 05 00:00:00 GMT+00:00 2018
Problem
date2 should be 6th of May (rather than 5th of June).
Since I have the timezone, is there a javascript function that will allow me to pass the date along with the timezone and it to automatically determine the correct date format (e.g dd/mm or mm/dd)?
I think the simple way to work with momentjs,
You can find example like this:
var a = moment.tz("2013-11-18 11:55", "America/Toronto");
var b = moment.tz("May 12th 2014 8PM", "MMM Do YYYY hA", "America/Toronto");
var c = moment.tz(1403454068850, "America/Toronto");

How to manipulate date in javascript

I'm having problem with manipulation of dates. I have a variable savedTime variable in localstorage wich contains this date:
Wed Aug 31 2016 16:31:30 GMT-0300 (Hora oficial do Brasil)
I need add 1 hour for this variable savedTime to check if passed 1 hour:
var savedTime = new Date(savedTime); //converts string to date object
var checkExpired = savedTime.setHours(savedTime.getHours() + 1); //add 1 hour to savedTime
But on trying add 1 hour to this variable converting the string in a object, this (savedTime) returns:
1472675490000
What i expected is the string with + 1 hour:
Wed Aug 31 2016 17:31:30 GMT-0300 (Hora oficial do Brasil)
And compare dates to check if passed 1 hour
var currentDate = new Date();
if(currentDate > checkExpired) {
//passed 1 hour
}
instance.setHours() manipulates the instance. So you can do
d = new Date('Wed Aug 31 2016 16:31:30 GMT-0300');
d.setHours(d.getHours() + 1);
Now d contains the new datetime.
setHours will manipulate the current object and return it's new value. Instead of using the return value, just continue to use the object.
var savedTime = new Date(savedTime); //converts string to date object
savedTime.setHours(savedTime.getHours() + 1); //add 1 hour to the savedTime
if (currentDate > savedTime) {
//passed 1 hour
}
Use .getTime()
if(currentDate.getTime() > checkExpired) {
//passed 1 hour
}
You are getting the value back in milliseconds from the 'epoch date' which is January first 1970.
If you want this in the correct format, you will need to parse this information out into that with some math / other Date object functions.
Here is the documentation to do that, it's very straightforward:
JS Date Formatting

Convert JavaScript new Date() to php DateTime()

I have 2 fields in HTML:
<input id="datum" type="date">
<input id="uhrzeit" type="time">
JavaScript:
var datumUhrzeit = new Date($("#datum").val()+","+$("#uhrzeit").val());
console.log(datumuhrzeit);
"Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)"
How can I convert "Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)" in PHP to a DateTime, so that I can save it to postgresql?
You can get unix timestamp from Date object as follows (see Date.prototype.getTime)
var timestamp = '#' + Math.round(datumUhrzeit.getTime()/1000);
Then when sent on server simply create new datetime object
$datumUhrzeit = new DateTime($timestamp);
If you can't use javascript to create timestamp and you get the the data from form directly you can do something like this, remember to set the timezone:
$datum = $_GET['datum'];
$uhrzeit = $_GET['uhrzeit'];
$datumUhrzeit = DateTime::createFromFormat('Y-m-d H:i:s', $datum . ' ' . $uhrzeit, new DateTimeZone('Europe/Berlin'));
Now as you have saved your date to the database and retrieved it, you can send it back
print $datumUhrzeit->format('U'); // This will print the time as unix timestamp
After that you would create your javascript date object with just the timestamp
var datumUhrzeit = new Date(timestamp * 1000); // timestamp from above
If you for some reason don't want to use unix timestamp you can print it in desired format with format method. Remember to set the timezone beforehand
$datumUhrzeit->setTimezone(new DateTimeZone('Europe/Berlin'));
print $datumUhrzeit->format('Y-m-d H:i:s');
Because javascript doesn't work well with timezones I would advocate you to use unix timestamps when you can. This way you have less problems with timezones.
You can use this javascript function to convert the dateObject or date string to your desired format:
/**
* Formats a dateObject or date string to Y-m-d date
* Example: Converts dateObject or date string Sat Aug 19 2017 00:00:00 GMT+0530 (India Standard Time) TO 2017-08-19
*/
function format_date( date )
{
if (typeof date == "string")
{
date = new Date(date);
}
var year = date.getFullYear();
var month = (1 + date.getMonth()).toString();
month = month.length > 1 ? month : '0' + month;
var day = date.getDate().toString();
day = day.length > 1 ? day : '0' + day;
return year+'-'+month+'-'+day;
}
var dateString = 'Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)';
var formattedDate = format_date(dateString);//returned formatted date is 2015-08-18
Then you can pass this formatted date to your PHP code where you can use function strtotime to convert this date to your desired format. For ex:
$myFormattedDate = date('d-m-Y', strtotime($_REQUEST['formattedDate']));
You can do something like
$datumUhrzeit = 'Tue Aug 18 2015 16:45:00 GMT+0200 (Mitteleuropäische Sommerzeit)';
$datumUhrzeit = substr($datumUhrzeit, 0, strpos($datumUhrzeit, '('));
$resultDate = date('Y-m-d h:i:s', strtotime($datumUhrzeit));
echo $resultDate;
try this one
function myFunction() {
var content = document.getElementById("datum").value+","+document.getElementById("uhrzeit").value;
console.log(content);
}

Unexpected Date result from using Number and Split

Why does the following code:
newDate = "2-24-2014";
var splitDate = newDate.split('-');
var dateObj = new Date(Number(splitDate[0]), Number(splitDate[1]) - 1, Number(splitDate[2]));
Produce the following?:
Sat Jun 05 1909 00:00:00 GMT+0100 (GMT Daylight Time)
I know the formatting but not the strange date itself. I was wondering if it had something to do with Number but cant seem to find any answers on this.
new Date(Year, Month, Date)
The above is the actual format. Whereas you have given like new Date(Month, Date, Year)
var dateObj = new Date(Number(splitDate[2]), Number(splitDate[0]) - 1, Number(splitDate[1]));
the problem is the order of parameters:
new Date(Number(splitDate[2]), Number(splitDate[0]) - 1, Number(splitDate[1]));
or simply do this:
new Date(Date.parse("2-24-2014"))

javascript date conversion showing wrong month

In the following date conversion after converting back the long integer The date says october instead of september
var date = 2013-09-23 18:31
startdate = getTimeStamp(date); //1382533260000
Now
t=1382533260000
rt = new Date(t)
//Wed Oct 23 2013 18:31:00 GMT+0530 (India Standard Time)
function getTimeStamp(strDate) {
var a1=strDate.split(" ");
var d1=a1[0].split("-");
var t1=a1[1].split(":");
var dtObj = new Date(d1[0],d1[1],d1[2],t1[0],t1[1]);
return dtObj.getTime();
}
In JavaScript, month numbers are numbered 0-11.
If you're parsing from components like this into the Date constructor you'll have to subtract one from the number:
function getTimeStamp(strDate) {
var a1=strDate.split(" ");
var d1=a1[0].split("-");
var t1=a1[1].split(":");
var dtObj = new Date(d1[0],d1[1] - 1,d1[2],t1[0],t1[1]);
return dtObj.getTime();
}
Months are zero-based, so January is zero, February is one, etc..
So you need to use d1[1]-1 in your new Date() constructor.
Javascript month parameter starts from 0 upto 11 so, passing 8 means september

Categories

Resources