Formatting milliseconds as date in couchDB map function - javascript

i am trying to convert milliseconds to my desired date format. But the format that i give to the function doesn`t seem to work.
In my map function
var date = new Date(item.showTime);
var dateString = date.toString('MM/dd/yy HH:mm:ss');
emit([doc.vehicleNumber,doc.advertId],{"seatNumber":item.seatNumber,"showTime":dateString ,"skipTime":item.skipTime});
});
The result is
{seatNumber: 2, showTime: "Tue Nov 21 2017 10:08:56 GMT+0000 (UTC)", skipTime: 0}
I need show time to in format of 10/12/2017 10:08:56.. I don`t know why this is not working.
Btw this is not javascript, i think it is about couchdb so please do
not mark this as duplicate with other JS questions.

CouchDB supports the use of CommonJS Modules in the map function definition.
http://docs.couchdb.org/en/2.1.1/query-server/javascript.html#commonjs
The problem is that modules should be defined in the design document and can not be loaded from external resources.
You can use standard JavaScript built-in objects and functions in your map function as couchjs is based in Mozilla's SpiderMonkey JS interpreter. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
There is not base support in CouchDB JS runtime for date formating. You should write your own logic for this purpose.
If this is a big issue for you, you may try to hack the /path/to/couchdb/share/server/main.js file which is the one that sets the execution contexts of your functions, but I don't see it too much recommendable.

Parse the date and format it yourself. It's not difficult.
var date = new Date(Date.parse(item.showTime));
var timestring = "" + date.getMonth() + "/" + date.getDate() + "/" +
date.getFullYear() + " " + date.toTimeString().substr(0,8)

This is very much about JavaScript. The .toString() method does not take any formatting parameters. You can write your own function to convert the output, or you can use a library that does what you want.

Related

Moment.js transform to date object

Using Moment.js I can't transform a correct moment object to a date object with timezones. I can't get the correct date.
Example:
var oldDate = new Date(),
momentObj = moment(oldDate).tz("MST7MDT"),
newDate = momentObj.toDate();
console.log("start date " + oldDate)
console.log("Format from moment with offset " + momentObj.format())
console.log("Format from moment without offset " + momentObj.utc().format())
console.log("(Date object) Time with offset " + newDate)
console.log("(Date object) Time without offset "+ moment.utc(newDate).toDate())
Use this to transform a moment object into a date object:
From http://momentjs.com/docs/#/displaying/as-javascript-date/
moment().toDate();
Yields:
Tue Nov 04 2014 14:04:01 GMT-0600 (CST)
As long as you have initialized moment-timezone with the data for the zones you want, your code works as expected.
You are correctly converting the moment to the time zone, which is reflected in the second line of output from momentObj.format().
Switching to UTC doesn't just drop the offset, it changes back to the UTC time zone. If you're going to do that, you don't need the original .tz() call at all. You could just do moment.utc().
Perhaps you are just trying to change the output format string? If so, just specify the parameters you want to the format method:
momentObj.format("YYYY-MM-DD HH:mm:ss")
Regarding the last to lines of your code - when you go back to a Date object using toDate(), you are giving up the behavior of moment.js and going back to JavaScript's behavior. A JavaScript Date object will always be printed in the local time zone of the computer it's running on. There's nothing moment.js can do about that.
A couple of other little things:
While the moment constructor can take a Date, it is usually best to not use one. For "now", don't use moment(new Date()). Instead, just use moment(). Both will work but it's unnecessarily redundant. If you are parsing from a string, pass that string directly into moment. Don't try to parse it to a Date first. You will find moment's parser to be much more reliable.
Time Zones like MST7MDT are there for backwards compatibility reasons. They stem from POSIX style time zones, and only a few of them are in the TZDB data. Unless absolutely necessary, you should use a key such as America/Denver.
.toDate did not really work for me, So, Here is what i did :
futureStartAtDate = new Date(moment().locale("en").add(1, 'd').format("MMM DD, YYYY HH:MM"))
hope this helps
Since momentjs has no control over javascript date object I found a work around to this.
const currentTime = new Date();
const convertTime = moment(currentTime).tz(timezone).format("YYYY-MM-DD HH:mm:ss");
const convertTimeObject = new Date(convertTime);
This will give you a javascript date object with the converted time
The question is a little obscure. I ll do my best to explain this. First you should understand how to use moment-timezone. According to this answer here TypeError: moment().tz is not a function, you have to import moment from moment-timezone instead of the default moment (ofcourse you will have to npm install moment-timezone first!). For the sake of clarity,
const moment=require('moment-timezone')//import from moment-timezone
Now in order to use the timezone feature, use moment.tz("date_string/moment()","time_zone") (visit https://momentjs.com/timezone/ for more details). This function will return a moment object with a particular time zone. For the sake of clarity,
var newYork= moment.tz("2014-06-01 12:00", "America/New_York");/*this code will consider NewYork as the timezone.*/
Now when you try to convert newYork (the moment object) with moment's toDate() (ISO 8601 format conversion) you will get the time of Greenwich,UK. For more details, go through this article https://www.nhc.noaa.gov/aboututc.shtml, about UTC. However if you just want your local time in this format (New York time, according to this example), just add the method .utc(true) ,with the arg true, to your moment object. For the sake of clarity,
newYork.toDate()//will give you the Greenwich ,UK, time.
newYork.utc(true).toDate()//will give you the local time. according to the moment.tz method arg we specified above, it is 12:00.you can ofcourse change this by using moment()
In short, moment.tz considers the time zone you specify and compares your local time with the time in Greenwich to give you a result. I hope this was useful.
To convert any date, for example utc:
moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()
let dateVar = moment('any date value');
let newDateVar = dateVar.utc().format();
nice and clean!!!!
I needed to have timezone information in my date string. I was originally using moment.tz(dateStr, 'America/New_York').toString(); but then I started getting errors about feeding that string back into moment.
I tried the moment.tz(dateStr, 'America/New_York').toDate(); but then I lost timezone information which I needed.
The only solution that returned a usable date string with timezone that could be fed back into moment was moment.tz(dateStr, 'America/New_York').format();
try (without format step)
new Date(moment())
var d = moment.tz("2019-04-15 12:00", "America/New_York");
console.log( new Date(d) );
console.log( new Date(moment()) );
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data.min.js"></script>
moment has updated the js lib as of 06/2018.
var newYork = moment.tz("2014-06-01 12:00", "America/New_York");
var losAngeles = newYork.clone().tz("America/Los_Angeles");
var london = newYork.clone().tz("Europe/London");
newYork.format(); // 2014-06-01T12:00:00-04:00
losAngeles.format(); // 2014-06-01T09:00:00-07:00
london.format(); // 2014-06-01T17:00:00+01:00
if you have freedom to use Angular5+, then better use datePipe feature there than the timezone function here. I have to use moment.js because my project limits to Angular2 only.
new Date(moment()) - could give error while exporting the data column in excel
use
moment.toDate() - doesn't give error or make exported file corrupt

Built-in function in Javascript to format date

I'm wondering if there is anything like this?
I'm getting my CMS to sort the content by date, so this is my approach.
First getting the current time.
var date = Date.now();
It will return me 1374426602321.
So now when I want to display that to the user and obviously we don't want to display the above, so I'm using this right now.
var formattedDate = new Date(date).toDateString(),
That will output
Sun Jul 21 2013
Which is good, but that is not really the correct or perfect way I guess.
I'm expecting more like Sunday July 21, 2013.
Is there a way that we can accomplish this by not using any of the plugin or any module and not having to create like another function to format this??
This is being done in the server-side using Node.js
use a library or a function... don't see any other way.
function getDateString(d){
return
["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][d.getDay()]+" "+
["January","February","March","April","May","June","July","August","September","October","November","December"][d.getMonth()]+" "+
d.getDate()+", "+
d.getFullYear();
}

Date format conversion javascript

Consider if we have a date in the format Sat Jul 28 2012 , is there a general a function to convert it in to any wanted format??
say for example 28-07-2012,
deciding the separators like - or /
Javascript's Date object has lots of different versions of toString and different getters, so it should be pretty easy to get the output you want. Scroll down through this documentation to see some of your options. They have pretty good examples too if you click on them.
In addition, the Date constructor is fairly good at taking in most strings and converting it.
var myDate = new Date("Sat Jul 28 2012");
alert(myDate.toLocaleDateString());
Or use the different getters and string concatenation wrapped in a function to make your own.
You can write a function to do it, i dont think there is a Native method:
function convert(dateObj) {
var format = dateObj.getFullYear()+"-";
format += dateObj.getMonth()+"-";
format += dateObj.getDate();
return format;
}
you can customize it however you want. here is the list of methods for the date object
Javascript only outputs it into the standard format you provided above. You can try using the getDate(), getDay(), getMonth() methods (among others) to extract the necessary data and convert it to your liking.
Please refer to W3Schools' description of the JavaScript Date object.

Javascript equivalent of php's strtotime()?

In PHP, you can easily convert an English textual datetime description into a proper date with strtotime().
Is there anything similar in Javascript?
There is not. The closest built-in option is Date.parse(), which parses a very limited subset of what strtotime() can:
var ts = Date.parse("2010-10-29");
It's worth noting that this function returns milliseconds instead of seconds, so you need to divide the result by 1000 to get an equivalent value to PHP's function.
I found this article and tried the tutorial. Basically, you can use the date constructor to parse a date, then write get the seconds from the getTime() method
var d=new Date("October 13, 1975 11:13:00");
document.write(d.getTime() + " milliseconds since 1970/01/01");
Does this work?
Check out this implementation of PHP's strtotime() in JavaScript!
I found that it works identically to PHP for everything that I threw at it.
Update: this function as per version 1.0.2 can't handle this case: '2007:07:20 20:52:45'
(Note the : separator for year and month)
Update 2018:
This is now available as an npm module! Simply npm install locutus and then in your source:
var strtotime = require('locutus/php/datetime/strtotime');
I jealous the strtotime() in php, but I do mine in javascript using moment. Not as sweet as that from php, but does the trick neatly too.
// first day of the month
var firstDayThisMonth = moment(firstDayThisMonth).startOf('month').toDate();
Go back and forth using the subtract() and add() with the endOf() and startOf():
// last day of previous month
var yesterMonthLastDay = moment(yesterMonthLastDay).subtract(1,'months').endOf('month').toDate();
Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.
Try Moment.js - it provides cross-browser functionality for parsing dates:
var timestamp = moment("2013-02-08 09:30:26.123");
console.log(timestamp.milliseconds()); // return timestamp in milliseconds
console.log(timestamp.second()); // return timestamp in seconds
There are few modules that provides similar behavior, but not exactly like PHP's strtotime. Among few alternatives I found date-util yields the best results.
var strdate = new Date('Tue Feb 07 2017 12:51:48 GMT+0200 (Türkiye Standart Saati)');
var date = moment(strdate).format('DD.MM.YYYY');
$("#result").text(date); //07.02.2017
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
<div id="result"></div>
Maybe you can exploit a sample function like :
function strtotime(date, addTime){
let generatedTime=date.getTime();
if(addTime.seconds) generatedTime+=1000*addTime.seconds; //check for additional seconds
if(addTime.minutes) generatedTime+=1000*60*addTime.minutes;//check for additional minutes
if(addTime.hours) generatedTime+=1000*60*60*addTime.hours;//check for additional hours
return new Date(generatedTime);
}
let futureDate = strtotime(new Date(), {
hours: 1, //Adding one hour
minutes: 45 //Adding fourty five minutes
});
document.body.innerHTML = futureDate;
`
For those looking to convert the datetime to unix timestamp, you can do this using the Moment Library.
For Vue.js, you can do something like
let start = "2022/02/02 02:02:02";
return moment(start).format("x");

strptime in Javascript

I have a date input field that allows the user to enter in a date and I need to validate this input (I already have server side validation), but the trick is that the format is locale dependent. I already have a system for translating the strptime format string to the the user's preference and I would like to use this same format for validating on the Javascript side.
Any ideas or links to a strptime() implementation in Javascript?
After a few days of googling I found this implementation which, although not complete, seems to handle all of the cases I have right now.
I've just added our php.js implementation of strptime(); I've tested it a bit, but it needs further unit testing. Anyhow, feel free to give it a shot; it should cover everything that PHP does (except for not yet supporting the undocumented %E... (alternative locale format) specifiers).
Note that it also depends on our implementation of setlocale() and array_map()...
https://github.com/kvz/phpjs/blob/master/functions/strings/setlocale.js
https://github.com/kvz/phpjs/blob/master/functions/array/array_map.js
Here is an example function that duplicates most of the functionality of strptime. The JavaScript date object generally will parse any date string you throw at it so you don't have to worry to much about that. So once you have a date object based off of your string you just push each element into a JS object and return it. This site has a good reference to the properties of the JavaScript date object: http://www.javascriptkit.com/jsref/date.shtml
function strptime(dateString){
var myDate = new Date(dateString);
return {tm_sec:myDate.getSeconds(),
tm_min: myDate.getMinutes(),
tm_hour: myDate.getHours(),
tm_mday: myDate.getDate(),
tm_mon: myDate.getMonth(),
tm_year: myDate.getFullYear().toString().substring(2),
tm_wday: myDate.getDay()};
}
var dateString = "October 12, 1988 13:14:00";
dateObj = strptime(dateString);
document.write("d:" + dateObj.tm_min + "/" + dateObj.tm_hour + "/" + dateObj.tm_mday + "/" + dateObj.tm_mon + "/" + dateObj.tm_year);

Categories

Resources