way to convert string to javascript's date object - javascript

Im getting time response value as from php
00:00:00 or 10:10:10
only time values(24 hours format)
I need to convert this as javascript date object . then only i can able to use with javascript . How can achive this?

Using Moment js we can achieve
var dateObj= moment('15:00:00', 'HH:MM:SS').toDate();
console.log(dateObj);
Out put
Mon Dec 01 2014 15:00:00 GMT+0530 (India Standard Time)

A JavaScript Date object requires a Date as well as a time, so you will need to provide that with your received PHP time.
I'm guessing that you'd just want to use the current Day, Month and Year, so we will:
var d = new Date();
var year = d.getFullYear();
var month = d.getMonth();
var day = d.getDate();
var msecs = d.getMilliseconds();
Of course, you can also use the UTC methods instead.
Now that you have all the information necessary for a Date object, but the hours, minutes and seconds, we can create those from your PHP-provided string:
var hours = /\d\d/.exec(str);
var mins = /(?!^)\d\d/.exec(str);
var secs = /\d\d$/.exec(str);
Now we have everything necessary to create our Date object, we can do so:
var ourDate = new Date(year, month, day, hours, mins, secs, msecs);
Ta - da!
See a working fiddle.

Related

why do I get 24? when I have a date "2015-10-23T23:59:57"

I have a Date Object "2015-10-23T23:59:57", invoke getDate(), it returns 24.
I am very confused.
Script
var d = new Date("2015-10-23T23:59:57");
var day = d.getDate();
alert(day);
new Date('2015-10-23T23:59:57') create UTC date. As per your timezone it must have been 24th Oct thus you are getting 24.
If you want to use the string to create Date, You can use momentjs library.
var cdt = moment('2015-10-23T23:59:57').toDate();
alert(cdt.getDate());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.3/moment.js"></script>

Setting Date in the Future with Javascript

I am trying to generate a future date based on a previously set date, but I am getting strange output.
var today = new Date(),
expiration = (today.getTime() + (3*60*1000),
theFuture = new Date();
//setup future time
theFuture.setDate(expiration);
console.log(theFuture);
//outputs something like:
Tue Jan d) -2147483647 20:33:52 GMT-0500 (EST)
Why is the date malformed here?
Ultimately I want to compare the dates, but something isn't right here.
The argument to setDate is the day of the month, while the return value of getTime is the number of milliseconds since Jan 1 1970. So you're setting the day of the month to something like 1437007985574, which is almost 4 billion years in the future. You get a nonsensical result because the date formatting functions aren't designed to handle such large dates, and they're overflowing internally.
Since you're using getTime to get the time in milliseconds, you should use setTime to set it the same way:
var today = new Date(),
expiration = today.getTime() + (3*60*1000),
theFuture = new Date();
//setup future time
theFuture.setTime(expiration);
alert(theFuture);
getDate() returns day of the month (between 1 and 31). Thats why setDate results in a malformed date

Convert Date and Time to Current Millis (JavaScript)

I'm using the Angular UI Bootstrap Datepicker and Timepicker (https://angular-ui.github.io/bootstrap/), and I want to combine both of those values and get the current millis. I get the date in this format: "2015-05-19" [YYYY-MM-DD"] and the time as this: "10:57:19" [HH:MM:SS].
I saw that there is a Date.parse() method where you can get current millis but I couldn't find a way where you can include a time as well, and was wondering if there was a method for this?
Since you already have a date and a time, you could use these to construct a date string:
var date = '1970-01-01';
var time = '00:00:00';
var dateString = date + 'T' + time; // '1970-01-01T00:00:00'
var parsedDate = Date.parse(dateString); // 0 Milliseconds
The 'T' is for handling timezones. Since I'm located in central Europe, my timezone offset is GMT+1 (Central European Time).
var newDate = new Date(parsedDate); // Thu Jan 01 1970 01:00:00 GMT+0100 (CET)
looks like the answer would be: Date.parse('MM DD YYYY HH:MM:SS');
from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
but you probably need to be wary of the time zone.

Parse date without timezone javascript

I want to parse a date without a timezone in JavaScript. I tried:
new Date(Date.parse("2005-07-08T00:00:00+0000"));
Which returned Fri Jul 08 2005 02:00:00 GMT+0200 (Central European Daylight Time):
new Date(Date.parse("2005-07-08 00:00:00 GMT+0000"));
returns the same result and:
new Date(Date.parse("2005-07-08 00:00:00 GMT-0000"));
also returns the same result.
I want to parse time:
without time zone.
without calling a constructor Date.UTC or new Date(year, month, day).
by simply passing a string into the Date constructor (without prototype approaches).
I have to produce a Date object, not a String.
I have the same issue. I get a date as a String, for example: '2016-08-25T00:00:00', but I need to have Date object with correct time. To convert String into object, I use getTimezoneOffset:
var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);
getTimezoneOffset() will return ether negative or positive value. This must be subtracted to work in every location in world.
The date is parsed correctly, it's just toString that converts it to your local timezone:
let s = "2005-07-08T11:22:33+0000";
let d = new Date(Date.parse(s));
// this logs for me
// "Fri Jul 08 2005 13:22:33 GMT+0200 (Central European Summer Time)"
// and something else for you
console.log(d.toString())
// this logs
// Fri, 08 Jul 2005 11:22:33 GMT
// for everyone
console.log(d.toUTCString())
Javascript Date object are timestamps - they merely contain a number of milliseconds since the epoch. There is no timezone info in a Date object. Which calendar date (day, minutes, seconds) this timestamp represents is a matter of the interpretation (one of to...String methods).
The above example shows that the date is being parsed correctly - that is, it actually contains an amount of milliseconds corresponding to "2005-07-08T11:22:33" in GMT.
I ran into the same problem and then remembered something wonky about a legacy project I was working on and how they handled this issue. I didn't understand it at the time and didn't really care until I ran into the problem myself
var date = '2014-01-02T00:00:00.000Z'
date = date.substring(0,10).split('-')
date = date[1] + '-' + date[2] + '-' + date[0]
new Date(date) #Thu Jan 02 2014 00:00:00 GMT-0600
For whatever reason passing the date in as "01-02-2014" sets the timezone to zero and ignores the user's timezone. This may be a fluke in the Date class but it existed some time ago and exists today. And it seems to work cross-browser. Try it for yourself.
This code is implemented in a global project where timezones matter a lot but the person looking at the date did not care about the exact moment it was introduced.
I found JavaScript Date Object and Time Zones | Fixing an "off by 1 day" bug on YouTube. This fixes/resets the offset for the local timezone. There's a great explanation to this problem in the video.
// date as YYYY-MM-DDT00:00:00Z
let dateFormat = new Date(date)
// Methods on Date Object will convert from UTC to users timezone
// Set minutes to current minutes (UTC) + User local time UTC offset
dateFormat.setMinutes(dateFormat.getMinutes() + dateFormat.getTimezoneOffset())
// Now we can use methods on the date obj without the timezone conversion
let dateStr = dateFormat.toDateString();
Since it is really a formatting issue when displaying the date (e.g. displays in local time), I like to use the new(ish) Intl.DateTimeFormat object to perform the formatting as it is more explicit and provides more output options:
const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
const dateFormatter = new Intl.DateTimeFormat('en-US', dateOptions);
const dateAsFormattedString = dateFormatter.format(new Date('2019-06-01T00:00:00.000+00:00'));
console.log(dateAsFormattedString) // "June 1, 2019"
As shown, by setting the timeZone to 'UTC' it will not perform local conversions. As a bonus, it also allows you to create more polished outputs. You can read more about the Intl.DateTimeFormat object in Mozilla - Intl.DateTimeFormat.
The same functionality can be achieved without creating a new Intl.DateTimeFormat object. Simply pass the locale and date options directly into the toLocaleDateString() function.
const dateOptions = { timeZone: 'UTC', month: 'long', day: 'numeric', year: 'numeric' };
const myDate = new Date('2019-06-01T00:00:00.000+00:00');
myDate.toLocaleDateString('en-US', dateOptions); // "June 1, 2019"
The Date object itself will contain timezone anyway, and the returned result is the effect of converting it to string in a default way. I.e. you cannot create a date object without timezone. But what you can do is mimic the behavior of Date object by creating your own one.
This is, however, better to be handed over to libraries like moment.js.
Date in JavaScript is just keeping it simple inside, so the date-time data is stored in UTC Unix epoch (milliseconds or ms).
If you want to have a "fixed" time that doesn't change in whatever timezone you are on the earth, you can adjust the time in UTC to match your current local timezone and save it. And when retrieving it, in whatever your local timezone you are in, it will show the adjusted UTC time based on the one who saved it and then add the local timezone offset to get the "fixed" time.
To save date (in ms):
toUTC(datetime) {
const myDate = (typeof datetime === 'number')
? new Date(datetime)
: datetime;
if (!myDate || (typeof myDate.getTime !== 'function')) {
return 0;
}
const getUTC = myDate.getTime();
const offset = myDate.getTimezoneOffset() * 60000; // It's in minutes so convert to ms
return getUTC - offset; // UTC - OFFSET
}
To retrieve/show date (in ms):
fromUTC(datetime) {
const myDate = (typeof datetime === 'number')
? new Date(datetime)
: datetime;
if (!myDate || (typeof myDate.getTime !== 'function')) {
return 0;
}
const getUTC = myDate.getTime();
const offset = myDate.getTimezoneOffset() * 60000; // It's in minutes so convert to ms
return getUTC + offset; // UTC + OFFSET
}
Then you can:
const saveTime = new Date(toUTC(Date.parse("2005-07-08T00:00:00+0000")));
// SEND TO DB....
// FROM DB...
const showTime = new Date(fromUTC(saveTime));
You can use this code
var stringDate = "2005-07-08T00:00:00+0000";
var dTimezone = new Date();
var offset = dTimezone.getTimezoneOffset() / 60;
var date = new Date(Date.parse(stringDate));
date.setHours(date.getHours() + offset);
Here's a simple solution:
const handler1 = {
construct(target, args) {
let newDate = new target(...args);
var tzDifference = newDate.getTimezoneOffset();
return new target(newDate.getTime() + tzDifference * 60 * 1000);
}
};
Date = new Proxy(Date, handler1);
The solution is almost the same as #wawka's, however it handles different timezones with plus and minus sings using Math.abs:
const date = new Date("2021-05-24T22:00:18.512Z")
const userTimezoneOffset = Math.abs(date.getTimezoneOffset() * 60000);
new Date(date.getTime() - userTimezoneOffset);
The only time new Date() does the time zone conversion is when you pass the time zone reference. For e.g. in the following string "2022-08-16T10:54:12Z" the Z at the end is a reference to timezone. If the object is passing this variable at the end, you can use the following code to get a new date object without time conversion:
const dateStr = '2022-07-21T09:35:31.820Z';
const date = new Date(dateStr);
console.log(date); // 👉️ Thu Jul 21 2022 12:35:31 GMT+0300
const result = new Date(date.toISOString().slice(0, -1));
console.log(result); // 👉️ Thu Jul 21 2022 09:35:31 GMT+0300
I would personally prefer #wawka's answer, however, I also came up with a not so clean trick to solve this problem, which is simpler and can work if you are sure about the format of the strings you want to convert.
Look at the code snippet below:
var dateString = '2021-08-02T00:00:00'
var dateObj = new Date(dateString + 'Z')
console.log("No Timezone manipulation: ", dateObj)
var dateObjWithTZ = new Date(dateString)
console.log("Normal conversion: ", dateObjWithTZ)
This works in this case, because adding a Z to the end of the date time string will make JS treat this string to be a UTC date string, so it does not add timezone difference to it.
Timezone is a part of Javascript. I used the following code to adjust the date according to the timezone.
var dt = new Date("Fri Mar 11, 2022 4:03 PM");
dt.setTime(dt.getTime() - dt.getTimezoneOffset() *60 * 1000); //Adjust for Timezone
document.write(dt.toISOString());
This is the solution that I came up with for this problem which works for me.
library used: momentjs with plain javascript Date class.
Step 1.
Convert String date to moment object (PS: moment retains the original date and time as long as toDate() method is not called):
const dateMoment = moment("2005-07-08T11:22:33+0000");
Step 2.
Extract hours and minutes values from the previously created moment object:
const hours = dateMoment.hours();
const mins = dateMoment.minutes();
Step 3.
Convert moment to Date(PS: this will change the original date based on the timezone of your browser/machine, but don't worry and read step 4.):
const dateObj = dateMoment.toDate();
Step 4.
Manually set the hours and minutes extracted in Step 2.
dateObj.setHours(hours);
dateObj.setMinutes(mins);
Step 5.
dateObj will now have show the original Date without any timezone difference. Even the Daylight time changes won't have any effect on the date object as we are manually setting the original hours and minutes.
Hope this helps.
(new Date().toString()).replace(/ \w+-\d+ \(.*\)$/,"")
This will have output: Tue Jul 10 2018 19:07:11
(new Date("2005-07-08T11:22:33+0000").toString()).replace(/ \w+-\d+ \(.*\)$/,"")
This will have output: Fri Jul 08 2005 04:22:33
Note: The time returned will depend on your local timezone
There are some inherent problems with date parsing that are unfortunately not addressed well by default.
-Human readable dates have implicit timezone in them
-There are many widely used date formats around the web that are ambiguous
To solve these problems easy and clean one would need a function like this:
>parse(whateverDateTimeString,expectedDatePattern,timezone)
"unix time in milliseconds"
I have searched for this, but found nothing like that!
So I created:
https://github.com/zsoltszabo/timestamp-grabber
Enjoy!

Formatting of Date using SimpleDateFormatter

I am using date function in javascript to get the currentDate.
as
var currentTime =new Date()
But it is giving me different response in IE and Firefox as
Consider for today's Date
IE - Tue 24 Apr 17:05:22 UTC 0530 2012
Mozilla - Tue 24 Apr 17:05:22 2012 GMT 0530
The Problem is that I Want to convert today's date which is in "String" to "Date" into format - EEE mmm-dd hh:mm:ss IST yyyy
But as i m getting different response in this browser I m not getting how to apply simpleDateformatter to convert current date and time to the suitable format .
You can use functions of object Date. For example:
var currentTime = new Date();
var date = currentTime.getDate();
var day = currentTime.getDay();
var hours = currentTime.getHours();
With help this functions you can convert current date and time to the suitable format.

Categories

Resources